【问题标题】:Binary Search Tree insertion using C++ Class Segmentation fault使用 C++ 类分段错误插入二叉搜索树
【发布时间】:2020-06-01 02:40:16
【问题描述】:

我正在尝试在 C++ 中实现二叉搜索树类的插入,但我不断遇到分段错误。我正在尝试只用一门课:

这是我的代码:

class BinarySearchTree{
public:
BinarySearchTree(int n);
BinarySearchTree* tree;
BinarySearchTree* right;
BinarySearchTree* left;
int treekey;
BinarySearchTree* insert(int n, BinarySearchTree*& thetree);
}

BinarySearchTree::BinarySearchTree(int n){
tree = new BinarySearchTree();
tree->left = NULL;
tree->right = NULL;
tree->treekey = n;
cout<<"Treekey is "<<tree->treekey<<endl;
}

BinarySearchTree* BinarySearchTree::insert(int n, BinarySearchTree*& thetree){
cout<<"the tree tree key now is "<<thetree->treekey<<endl;
if(thetree == NULL){
    cout<<"is empty"<<endl;
    tree = new BinarySearchTree(n);
    return tree;
}
cout<<"not empty"<<endl;
cout<<"Treekey here is "<<thetree->treekey<<endl;
if(n<thetree->treekey){
    thetree->left = insert(n, thetree->left);
}else{
    thetree->right = insert(n, thetree->right);
}
return thetree;
}



int main(){
BinarySearchTree* newtree= new BinarySearchTree(16);
newtree -> insert(13, newtree);
return 0;
}

我当前的代码输出:

Treekey is 16
the tree tree key now is -1550649400 
not empty
Treekey here is -1550649400
Segmentation fault: 11

对不起,我真的很陌生。请帮我解决这个问题,谢谢!

【问题讨论】:

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


    【解决方案1】:

    您的代码基本上没问题,只是当您无条件访问theTree 的成员时调用了未定义的行为。只需在检查后移动该行:

    BinarySearchTree* BinarySearchTree::insert(int n, BinarySearchTree*& thetree){
      if(thetree == NULL){
         // ... 
      }
      cout<<"the tree tree key now is "<<thetree->treekey<<endl;
      // ^^^^ moved this line to after the if
    

    此外,您缺少类的默认构造函数。您可以通过以下方式恢复它:

    BinarySearchTree() = default;
    

    此外,您应该为所有成员使用默认值:

    BinarySearchTree* tree = nullptr;
    BinarySearchTree* right = nullptr;
    BinarySearchTree* left = nullptr;
    int treekey{};
    

    请注意,您应该在代码中使用 nullptr 而不是 NULL

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多