【发布时间】:2018-11-11 16:41:51
【问题描述】:
我有两个函数遍历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 循环 i)
可能是什么问题?我的帖子和预购有什么不同?
【问题讨论】:
-
从算法的角度来看,它看起来不错。我认为现在是一个最小、完整和简洁的例子的时候了。 . .
-
你能把失败的用例和主要的用例贴出来吗? (创建 dataArray 和函数用法)分段错误发生在函数的开头还是中间?你有任何指纹吗?
-
我已经编辑了帖子以包含我的所有代码@DavidWinder
-
@gsamaras 我已经相应地编辑了帖子。
-
这就是为什么你现在得到了一个答案,很好,很好的问题!
标签: c tree segmentation-fault tree-traversal