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 "\0";
}
我正在制作一个二叉搜索树。但是,当我运行我的搜索功能时,即使值存在于树中,它也总是返回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();
}
当你使用树时,索引的类型是什么? – speeder 2013-02-23 20:46:18
它是int类型。 – User14229754 2013-02-23 20:48:55