2017-06-19 71 views
0

我目前正在研究二叉搜索樹的C++實現。一切看起來都很完美,但我的搜索功能給了我很多問題。C++ Segmentation fault BST

BinarySearchTree::node* BinarySearchTree::SEARCH(node* x, int key) 
{ 
    if(root == NULL) { 
      cout << "This is an empty tree." << endl; 
      return NULL; 

    } else { 
      if(x->key == key) { 
        return x; 
      } 
      if(x == NULL) { 
        cout << "Value not in tree." << endl; 
        return x; 
      } 
      if(key < x->key) { 
        return SEARCH(x->left, key); 
      } else { 
        return SEARCH(x->right, key); 
      } 
    } 
} 

這給了我一個分段錯誤每次我要尋找的,是不是在樹中的鍵值時,當節點值爲NULL(如值,這將是無論是最大,或者如果它閔被包括在內)。

+0

聽起來像你需要使用調試器。並且在解除引用後檢查'x'是否爲空。 –

+0

我從來沒有在UNIX環境中使用調試器,假設我應該找出如何通過現在= P來做到這一點。 – DJWright97

回答

0

先檢查NULL指針,然後檢查其餘指針。如果x爲NULL,則按x->key訪問密鑰會導致分段錯誤。

if(x == NULL) { 
    cout << "Value not in tree." << endl; 
    return x; 
} 
if(x->key == key) { 
    return x; 
} 
... 
+0

當它!我知道這會是我失蹤的愚蠢。謝謝。 – DJWright97

相關問題