C++ 树的奇怪行为
下面的代码让我很困惑 阶级 插入函数C++ 树的奇怪行为,c++,avl-tree,C++,Avl Tree,下面的代码让我很困惑 阶级 插入函数 AVLTree::AVLNode* AVLTree::insert(int d,AVLNode *n){ if (n == NULL) { AVLNode *n = new AVLNode; n->data = d; n->leftchild = NULL; n->rightchild = NULL; n->height = 0;
AVLTree::AVLNode* AVLTree::insert(int d,AVLNode *n){
if (n == NULL)
{
AVLNode *n = new AVLNode;
n->data = d;
n->leftchild = NULL;
n->rightchild = NULL;
n->height = 0;
} else if( d < n->data) {
n->leftchild = insert(d,n->leftchild);
} else if (d > n->data) {
n->rightchild = insert(d,n->rightchild);
}
else {
n->height = max(height(n->leftchild), height(n->rightchild));
return n;
}
-----> This section of the code gives be "EXC_BAD_ACCESS".
n->height = max(height(n->leftchild), height(n->rightchild));
return n;
}
int AVLTree::height(AVLNode* node)
{ cout << "HEIGHT";
if(node == NULL)
{
return -1;
}
else {
return node->height;
}
}
它似乎没有像应该的那样交换值。虽然n=child似乎在本地交换,但它并不反映代码其余部分的更改。给我一个无限循环。如果函数输入时
n
为空,则该行将尝试取消引用它,并给出错误。要分配新节点的代码应该将其分配给n
本身,而不是一个单独的变量,该变量具有与函数参数相同的名称
将if(n==NULL)
块的第一行从
AVLNode *n = new AVLNode;
到
关于更新:在rotate函数中,
n
是一个本地(自动)变量,更改该变量不会影响函数之外的任何内容。您需要通过引用传递指针,或者返回新的指针值(就像您在insert()
中所做的那样)。您的具体问题是什么?您是否使用调试器逐步完成了函数以查看发生了什么事?”下面的代码让我非常困惑。[…]有人知道原因吗?“嗯……我想说:“因为你不懂代码。”现在,也许你可以更具体地问我们你不懂什么?为什么它会给“EXC\u BAD\u ACCESS”“在运行两次之后。请在评论之前阅读插入函数…当您使用调试器逐步执行该函数时,EXC\u BAD\u访问之前发生了什么?所有指针都指向有效节点吗?取消引用的指针是否为空或无效?如果是这样,指针是如何变为null或无效的,或者您忘记将其设置为指向有效节点的位置的?这确实很有帮助。但还有一些事情我不确定。
void AVLTree::rotateLeft(AVLNode* n)
{
AVLNode *child = n->leftchild;
n->leftchild = child->rightchild;
child->rightchild = n;
n->height = max(height(n->leftchild),height(n->rightchild))+1;
child->height = max(height(child->leftchild),height(child->rightchild))+1;
n = child;
}
AVLNode *n = new AVLNode;
n = new AVLNode;