2013-02-23 157 views
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(); 
} 
+0

當你使用樹時,索引的類型是什麼? – speeder 2013-02-23 20:46:18

+0

它是int類型。 – User14229754 2013-02-23 20:48:55

回答

0

首先,這並不在構造函數中的歸屬。這應該在readFile()方法或一些operator>>()

現在你讀功能

請勿檢查

while (!fin.eof()) 

做一次檢查上

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

代替。

最後,你永遠不會向你的樹添加任何東西,只有一些temp變量。這可能是搜索功能失敗的原因。

+0

我沒有顯示搜索功能 – User14229754 2013-02-23 20:49:52

+0

SearchNode()是搜索功能 – User14229754 2013-02-23 20:50:27

+0

@ User14229754是的,這是我的錯。我在二讀時發現它。我已經刪除了該評論。 – 2013-02-23 20:52:31