【发布时间】: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->left == NULL之前你应该检查current == NULL
标签: c++ insert segmentation-fault binary-search-tree