我有两个函数可以遍历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循环的原因)
有什么问题吗?我的邮件和预订有什么不同?
发布于 2018-11-11 20:49:03
请注意:当complete_post_b = postorder_recursive(b, post_order_b);在main的开头定义为:int* complete_post_b;时:main
但是,在postorder_recursive,you 不返回任何数据。因此,当辅助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时。我猜在这种情况下,返回值的寄存器将包含数据数组。当递归函数调用位于函数的末尾时,数据数组的地址停留在寄存器中并向前传输--但是您不能指望它,如果要使用它,就需要实际返回地址。
https://stackoverflow.com/questions/53250899
复制相似问题