gpt4 book ai didi

C++ 将第二个元素添加到 BST - 段错误

转载 作者:行者123 更新时间:2023-12-03 07:21:04 26 4
gpt4 key购买 nike

所以我根据类里面的例子构建了一个 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;
}

最佳答案

这是建立在 SHR 所说的基础上的。当您执行 current = current->left 行时,有可能current->left上一个电流是 null .
这意味着当您执行检查 if (current->left == NULL) ,会导致段错误,因为没有left .
您可以将条件重写为:

if (current && !current->left){
...
}
通过这样做,您首先检查是否 current不为空,如果为空,那么它才会查看节点的左指针。或者您也可以事先查看 if (current) .
检查 NULL 也完全足够并鼓励通过执行 if (node)而不是做 if (node == NULL) .这解释了原因: Checking for NULL pointer in C/C++

关于C++ 将第二个元素添加到 BST - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65095143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com