我正在尝试在C ++中为Binary Search Tree类实现插入,但是我一直遇到分段错误。我正在尝试只上一堂课:
这是我的代码:
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
抱歉,我真的很陌生。请帮助我,谢谢!
您的代码基本上没问题,除了您无条件访问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
。