我有两个函数在 preorder
和 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 循环 for i 的原因)
可能是什么问题?我的邮寄和预购有什么不同?
最佳答案
注意你这样做: 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
的唯一时间是节点为 null 时。我的猜测是在那种情况下,返回值的寄存器将包含数据数组。当在函数末尾调用递归函数时,数据数组的地址保留在寄存器中并向前传输 - 但你不能指望这一点,如果你想使用它,你需要实际返回地址
关于c - 前序树遍历有效但后序无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53250899/