【发布时间】: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