【问题标题】:C++ Segmentation fault BSTC++ 分段错误 BST
【发布时间】:2017-06-19 01:34:21
【问题描述】:

我目前正在研究二叉搜索树的 C++ 实现。一切似乎都运行良好,但我的搜索功能给我带来了问题。

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 时(例如,如果包含它,则该值将是最大值或最小值)时,这会给我一个分段错误。

【问题讨论】:

  • 听起来你需要使用调试器。并且您正在检查 x 在取消引用后是否为空。
  • 我从来没有在 UNIX 环境中使用过调试器,我想我现在应该知道该怎么做了 =P。

标签: c++ segmentation-fault binary-search-tree


【解决方案1】:

先检查 NULL 指针,然后检查其余部分。如果 x 为 NULL,则通过 x-&gt;key 访问 key 会导致分段错误。

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

【讨论】:

  • 该死!我知道这将是我错过的一些愚蠢的事情。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多