【问题标题】:C++ Adding 2nd Element to BST - Segmentation FaultC++ 将第二个元素添加到 BST - 分段错误
【发布时间】:2020-12-01 17:08:26
【问题描述】:

所以我根据课堂上的示例构建了一个 BST。我的同行的树都工作正常,但是,当我添加第二个元素时,我遇到了分段错误。我已经隔离了来自这一行的错误 - 'if(current->left == NULL){' 我不确定它为什么会导致分段错误以及如何避免它。我会留下相关的 insertNode 代码以及 Node 类,因为我觉得那里可能有问题。

template <class T>
void BST<T>::insertNode(T value){
  TreeNode<T> *node = new TreeNode<T>(value);


  if(isEmpty()){
    cout << "Is root" << endl;
    root = node;
  }else{
    cout << "Is not root" << endl;
    TreeNode<T> *parent = NULL;
    TreeNode<T> *current = root;
    cout << "Starting Loop" << endl;
    while(true){
      parent = current;

      if(value < current->key){
        cout << "less tahn" << endl;
        //Left
        current = current->left;
        cout <<"left" << endl;
        if(current == NULL){
          //we found our location/insertion point
          cout << "Found Spot" << endl;
          parent->left = node;
          break;
        }
        cout << "Not NULL" << endl;
      }
      else {
        //Right
        cout << "Right" << endl;
        current = current->right;
        if(current == NULL){
          //we found our location/insertion point
          cout << "Found Spot" << endl;
          parent->right = node;
          break;
        }
      }
    }
  }
}

还有treeNode类-

template <class T>
class TreeNode{
  public:
    TreeNode();
    TreeNode(T k);
    ~TreeNode();

    T key;
    TreeNode *left;
    TreeNode *right;
};
template <class T>
TreeNode<T>::TreeNode(){
  left = NULL;
  right = NULL;
}

template <class T>
TreeNode<T>::TreeNode(T k){
  left = NULL;
  right = NULL;
  key = k;
}

【问题讨论】:

  • 在你检查current-&gt;left == NULL之前你应该检查current == NULL

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


【解决方案1】:

这建立在 SHR 所说的基础上。当你执行current = current-&gt;left这行时,有可能之前当前的current-&gt;leftnull

这意味着当你执行检查if (current-&gt;left == NULL)时,会导致分段错误,因为没有left

您可以将条件重写为:

if (current && !current->left){
...
}

通过这样做,您首先检查current 是否不为空,如果是,那么它才会查看节点的左指针。或者您也可以事先查看if (current)

通过执行if (node) 而不是执行if (node == NULL) 来检查NULL 也完全足够并鼓励。这解释了原因:Checking for NULL pointer in C/C++

【讨论】:

  • 谢谢!这是很多非常有用的信息。我替换了您提供的代码,但是我仍然遇到了一些麻烦。现在,它只是跳过了 if 语句,因为它现在不是真的。然而,如果没有电流,它应该将节点插入树而不是中止插入,这很公平。我应该把 current = current->left 放在 if 语句之后吗?它似乎有效,但我不确定树是否正确保持其结构。谢谢!
  • EDIT - 刚刚测试过它似乎没有插入任何东西。如果 current 设置为 root,是不是 root 存储不正确?
猜你喜欢
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多