[英]Binary Search Tree(search function returning NULL)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
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();
void LoadTree(const char file[]);
~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>
BinaryTree<T>::BinaryTree()
{
Root=NULL;
}
template <class T>
void BinaryTree<T>::LoadTree(const char *file)
{
ifstream fin;
fin.open(file);
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;
if (temp->key>buff)
{
temp=temp->LeftChild;
}
else if (temp->key<buff)
{
temp=temp->RightChild;
}
}
temp=new TreeNode<T>(buff,buffer);
if (temp!=Root)
temp->Parent=temp1;
cout<<temp->value<<temp->key<<endl;
if (temp->LeftChild!=0)
cout<<(temp->LeftChild)->value<<endl;
}
fin.close();
}
template <class T>
string BinaryTree<T>::searchNode(T Key)
{
TreeNode<T> *temp=Root;
while (temp!=NULL)
{
if (temp->key==Key)
{
return temp->value;
}
if (temp->key>Key)
{
temp=temp->LeftChild;
}
else if (temp->key<Key)
{
temp=temp->RightChild;
}
}
return "\0";
}
Above are the header file and constructor and functions for building tree from a file and searching a node in it.I don't understand what am I missing in my function because whenever i run the search function,it always returns NULL which is the default condition when the node key exists in the file/tree. 上面是头文件和构造函数和函数,用于从文件构建树并搜索其中的节点。我不明白我的函数中缺少什么,因为每当我运行搜索函数时,它总是返回NULL,这是默认的当节点密钥存在于文件/树中时的条件。 Thanks a lot everyone,it's working now.I am really grateful.I used my insert function to build up my tree.
非常感谢大家,它现在正在工作。我真的很感激。我使用插入功能来构建我的树。
template <class T>
void BinaryTree<T>::insertNode(T Key,string Val)
{
TreeNode<T> **temp=&Root;
TreeNode<T> *temp1=NULL;
if (*temp==NULL)
{
Root=new TreeNode<T>(Key,Val);
return;
}
else{
while (*temp!=NULL)
{
temp1=*temp;
if (temp1->key>Key)
{
temp=&(*temp)->LeftChild;
}
else if (temp1->key<Key)
{
temp=&(*temp)->RightChild;
}
}
}
*temp=new TreeNode<T>(Key,Val);
(*temp)->Parent=temp1;
}
template <class T>
void BinaryTree<T>::LoadTree(const char *file)
{
ifstream fin;
fin.open(file);
string buffer;
T buff;
while (!fin.eof())
{
getline(fin,buffer,'~');
fin>>buff;
insertNode(buff,buffer);
}
fin.close();
}
Your Root
member never gets set. 您的
Root
成员永远不会被设置。 Thus its value is still NULL
when you try to search the tree, and the while
will never get entered. 因此,当您尝试搜索树时,其值仍为
NULL
,并且永远不会输入while
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.