![](/img/trans.png)
[英]Tree traversal (preorder,inorder,postorder) print result change
[英]Preorder tree traversal works but postorder doesn't
我有两个函数以preorder
和postorder
遍历树,每个函数将节点中的值插入到一个数组中,并返回该数组。
但是,我的postorder
功能不起作用。 调用该函数时出现分段错误。
编译并运行以下代码时,但在调用postorder
方法postorder
出现分段错误。
这是我的代码:
int* preorder_recursive(node *root, int* dataArray)
{
if (root == NULL)
return dataArray;
for (int i = 0; i < 512; i++)
{
if (dataArray[i] == INT_MIN)
{
dataArray[i] = root->data;
printf("%d is being inserted to the preorder array at pos %d\n", root->data, i);
break;
}
}
preorder_recursive(root->left, dataArray);
preorder_recursive(root->right, dataArray);
}
int* postorder_recursive(node *root, int *dataArray)
{
if (root == NULL)
return dataArray;
postorder_recursive(root->left, dataArray);
postorder_recursive(root->right, dataArray);
for (int i = 0; i < 512; i++)
{
// any "empty" spots in the array should contain INT_MIN
if (dataArray[i] == INT_MIN)
{
dataArray[i] = root->data;
printf("%d is being inserted to the postorder array at pos %d\n", root->data, i);
break;
}
}
}
调用时:
int * complete_pre_b = preorder_recursive(b, pre_order_b);
for(int i = 0; i < 3; i++)
{
printf("pre b is %d\n", complete_pre_b[i]);
}
int * complete_post_b = postorder_recursive(b, post_order_b);
// here is the last print I see - code get till here fine
for(int i = 0; i < 3; i++)
{
printf("post b is %d\n", complete_post_b[i]);
}
(注意- 我有 3 个节点的树,为什么我从 0 到 3 循环)
可能是什么问题? 我的post和pre order有什么不同?
请注意,您这样做: complete_post_b = postorder_recursive(b, post_order_b);
当complete_post_b
在main
的开头定义为: int* complete_post_b;
但是,在postorder_recursive
您不返回任何数据。 所以当分配给complete_post_b
它实际上是无效的。
你的 for 循环应该是:
for(int i = 0; i < 3; i++)
{
printf("post b is %d\n", post_order_b[i]); // and not complete_post_b
}
或者您可以返回dataArray
并使用complete_post_b
。
对于兴趣部分:为什么它只发生在 postOrder 上?
请注意,只有当节点为空时才返回dataArray
。 我的猜测是在这种情况下,返回值的寄存器将包含数据数组。 在函数末尾进行递归函数调用时,数据数组的地址保留在寄存器中并向前传输 - 但您不能指望这一点,如果您想使用它,您需要实际返回地址
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.