2014-02-19 30 views
-1

我已經實現了我的搜索功能。當我搜索一個不存在的值時,搜索功能可以查找並返回false。當我搜索一個值是根的工作正常,並返回true。問題是當我搜索一個值,而不是已經在樹中的根,但它返回false。任何想法做什麼即時錯誤?二叉搜索樹:搜索函數問題

template <class Comparable> 
bool BinarySearchTree<Comparable>::findValue(const Comparable& value){ 
if(root->element == value){ 
    return true; 
} 

if(value > root->element) 
{ 
    if(root->right != NULL) 
    { 
     root->right->findValue(value); 
    } 
    else 
    { 
     return false; 
    } 

} 
if(value < root->element) 
{ 
    if(root->left != NULL) 
    { 
    root->left->findValue(value); 
    } 
    else 
    { 
     return false; 
    } 

這些是我的私人數據成員,不能以任何方式進行修改。

private: 
struct BinaryNode 
{ 
    Comparable element; 
    BinarySearchTree<Comparable> *left; 
    BinarySearchTree<Comparable> *right; 
}; 
BinaryNode *root; 
}; 

回答

1

當你從正確的節點return false,你甚至不會嘗試左節點。

嘗試返回true而不是;

if(value > root->element) 
{ 
    if(root->right != NULL) 
    { 
     if(root->left->findValue(value)) 
     { 
      return true; 
     } 
    } 
} 
if(value < root->element) 
{ 
    if(root->left != NULL) 
    { 
     if(root->left->findValue(value) 
     { 
      return true; 
     } 
    } 
} 
return false 
+0

我試過你說的,我得到了同樣的結果。 – Frontier

1

你應該返還root->left->findValue(value);root->right->findValue(value)

目前您所要求的那些節點findValue功能,而不是存儲值或任何其返回所以結果正在喪失的結果。

+0

我試過你說的,但它仍然不能正常工作 對不起,這裏是使用合適的pastebin編輯http://pastebin.com/CQhAw7CF – Frontier