简体   繁体   中英

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 "\0";
}

I am making a binary search tree. But when I run my search function, it always returns NULL value even when the value exists in the tree. Either my constructor is not right or there is something wrong with my search function. I can't seem to figure out the problem. Here is the constructor:

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();
}

First of all, this doesn't belong in a constructor. This should be in a readFile() method or some operator>>() .

Now to your read function

Don't check on

while (!fin.eof())

do a check on

while (std::getline(fin, buffer, '~'))

instead.

And finally, you never add anything to your tree, only to some temp variables. This might be the reason for the failure of your search function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM