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

1 に答える 1

0

まず、これはコンストラクタには属しません。これは、readFile()メソッドまたは一部にある必要がありますoperator>>()

今、あなたの読み取り機能に

チェックしないで

while (!fin.eof())

チェックをする

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

代わりは。

最後に、ツリーには何も追加せず、いくつかのtemp変数にのみ追加します。これが、検索機能の失敗の原因である可能性があります。

于 2013-02-23T20:46:24.697 に答える