我有两个函数遍历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)
可能是什么问题?我的发布和预订之间有什么区别?
答案 0 :(得分:1)
请注意,您在complete_post_b = postorder_recursive(b, post_order_b);
的开头将complete_post_b
定义为:main
但是,在int* complete_post_b;
,您不要返回任何数据。因此,当辅助postorder_recursive
时,它实际上是无效的。
您的for循环应为:
complete_post_b
或者您可以返回for(int i = 0; i < 3; i++)
{
printf("post b is %d\n", post_order_b[i]); // and not complete_post_b
}
并使用dataArray
。
对于感兴趣的部分:为什么仅在postOrder上发生?
请注意,唯一返回complete_post_b
的时间是节点为null时。我的猜测是在这种情况下,用于返回值的寄存器将包含数据数组。在函数的末尾进行递归函数调用时,数据数组的地址会保留在寄存器中并向前传输-但是您不能指望该地址,并且如果要使用它,则需要实际返回地址