C++ 在顺序后继的递归代码中查找seg错误
嘿,伙计们,我只是在二进制搜索树上练习递归代码。我遇到了seg故障,但我不确定问题出在哪里(可能是某个愚蠢的东西正盯着我看)。我还有其他一些功能可以正常工作,比如计算节点数或计算树的高度。尤其是这个功能给我带来了麻烦。我用C++编写代码。C++ 在顺序后继的递归代码中查找seg错误,c++,recursion,segmentation-fault,inorder,C++,Recursion,Segmentation Fault,Inorder,嘿,伙计们,我只是在二进制搜索树上练习递归代码。我遇到了seg故障,但我不确定问题出在哪里(可能是某个愚蠢的东西正盯着我看)。我还有其他一些功能可以正常工作,比如计算节点数或计算树的高度。尤其是这个功能给我带来了麻烦。我用C++编写代码。 //wrapper function int table::in_order_successor() { node * temp; temp = root; in_order_successor(root, temp); } //
//wrapper function
int table::in_order_successor()
{
node * temp;
temp = root;
in_order_successor(root, temp);
}
//Find the in-order successor
int table::in_order_successor(node * root, node * temp)
{
if(root == NULL) return 0;
if(root->right != NULL)
if(root->data == temp->data)
in_order_successor(root, temp->right);
in_order_successor(root, temp->left);
return temp->data;
}
我的想法是让函数从根开始向右移动一次,然后尽可能向左继续。为了让它正确运行一次,我只想在root->data等于temp->data时正确运行(数据只是随机生成的int) 对于Seg故障,您应该检查
temp
是否为null
,因为您的代码可能会将temp->right
和temp->left
传递给它,这可能是null
if(temp == NULL) return 0; // add this check
但是代码中还有另一个问题:您永远不会重用返回值。然后它将只是迭代。假设您希望在遍历之后返回存储在叶节点中的数据,那么代码可能如下所示:
//Find the in-order successor
int table::in_order_successor(node * root, node * temp) {
if(root == NULL) return 0;
if(temp == NULL) return 0; // add this check
if(root->right != NULL) {
// check by pointer instead of the data unless each
// node->data is unique. Otherwise unwanted moving
// right will occur.
if(root == temp) {
if (temp->right != null) {
// use `return` here instead of plain function call to get
// the update of the rest of the recursion.
return in_order_successor(root, temp->right);
}
}
}
if (temp->left != null) {
// if have left child, return what you will find in the next step
return in_order_successor(root, temp->left); // use return here
} else {
// reach the left-most leaf after first steping right at root node.
return temp->data;
}
}
也
及
他只想从根开始向右走一次,然后尽可能地继续向左走,所以我认为这部分OP中的代码可能是正确的。添加这一点使代码不再是seg错误。很好,但是现在我只在最后返回根的数据。是的,我已经编辑了我的答案。问题是您从未使用返回的值。你应该按顺序返回,而不是仅仅称之为接班人……这似乎有效。我不习惯在这样的函数中间使用返回,所以我想我知道我现在需要练习什么了。谢谢@用户2484019:欢迎您。返回值有许多有趣的用法,例如将它们包含在一个公式中,如:
returnfoo(temp->left)+foo(temp->right)
@用户2484019顺便说一句,如果你不介意投票支持我的答案,那将是我的荣幸:)我不确定你是否仍然遵循我的答案。我已经编辑了我的答案很多次,希望这个版本适合你。
if(temp->left != NULL)
in_order_successor(root, temp->left);
if(!temp-> left)
return temp->data;