二进制搜索树(搜索功能)
Binary Search Tree (search function)
template <class T>
struct TreeNode{
string value;
T key;
TreeNode<T> *Parent;
TreeNode<T> *LeftChild;
TreeNode<T> *RightChild;
TreeNode (T k,string Val)
{
this->value=Val;
this->key=k;
this->Parent=NULL;
this->LeftChild=NULL;
this->RightChild=NULL;
}
};
template <class T>
class BinaryTree{
private:
TreeNode<T> *Root;
public:
BinaryTree();
~BinaryTree();
void insertNode(T Key,string Val);
void deleteNode(T Key);
string searchNode(T Key);
void UpdateKey(T newkey,T oldkey);
int Height(TreeNode<T> *node);
int height();
};
template <class T>
string BinaryTree<T>::searchNode(T Key)
{
TreeNode<T> *temp=Root;
while (temp!=NULL)
{
if (temp->key==Key)
{
cout<<temp->key<<endl;
return temp->value;
}
if (temp->key>Key)
{
temp=temp->LeftChild;
}
else if (temp->key<Key)
{
temp=temp->RightChild;
}
}
return " ";
}
我正在制作一个二进制搜索树。但是,当我运行搜索函数时,它总是返回NULL值,即使该值存在于树中。要么我的构造函数不对,要么我的搜索函数有问题。我似乎想不通这个问题。这是构造函数:
template <class T>
BinaryTree<T>::BinaryTree()
{
Root=NULL;
ifstream fin;
fin.open("names.txt");
string buffer;
T buff;
while (!fin.eof())
{
getline(fin,buffer,'~');
fin>>buff;
TreeNode<T> *temp,*temp1;
temp=Root;
temp1=temp;
while (temp!=NULL)
{
temp1=temp;
TreeNode<T> *Right=temp->RightChild;
TreeNode<T> *Left=temp->LeftChild;
if (temp->key>buff)
{
temp=temp->LeftChild;
}
else if (temp->key<buff)
{
temp=temp->RightChild;
}
else
{
temp=temp->LeftChild;
}
}
if (temp!=Root)
temp->Parent=temp1;
temp=new TreeNode<T>(buff,buffer);
}
fin.close();
}
首先,这不属于构造函数。这应该是在readFile()
方法或某些operator>>()
中。
现在转到您的读取功能
不检查
while (!fin.eof())
检查
while (std::getline(fin, buffer, '~'))
相反。
最后,您永远不会向树添加任何内容,只会向一些temp
变量添加任何内容。这可能是您的搜索功能失败的原因。
相关文章:
- 防弹站树搜索功能C++
- 迭代向量以获得搜索功能
- Sinlge 链表,C++,删除所有和搜索功能的问题
- 二叉搜索树 - 使用 Linux 在虚拟机中制作删除功能
- 如何将搜索功能添加到数组中
- 搜索非二进制树C 的功能
- 搜索功能使程序崩溃
- 替罪羊搜索功能
- 二叉搜索功能始终返回 -1 值而不是索引
- 用于二分搜索的错误简单功能(C++)
- 如何改进我的矢量搜索功能
- 按元素的功能搜索upper_bound
- 简单的二进制搜索树非递归添加功能
- 链接列表中的搜索功能问题
- 如何将搜索功能添加到WXWIDGET C 中的TextCtrl
- 二进制搜索功能不起作用
- 二叉搜索树在插入功能方面有问题
- 这个树搜索功能让我发疯.它返回 NULL,但不知何故主函数中的值发生了变化
- 看不懂二叉搜索功能
- C++ 二叉搜索功能不打印