2017-06-19 73 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

相关问题