【问题标题】:Preorder tree traversal works but postorder doesn't前序树遍历有效,但后序无效
【发布时间】:2018-11-11 16:41:51
【问题描述】:

我有两个函数遍历preorderpostorder 中的树,每个函数都将节点中的值插入到数组中,然后返回数组。

但是,我的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


【解决方案1】:

请注意:complete_post_b = postorder_recursive(b, post_order_b);complete_post_bmain 的开头定义为: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 的唯一时间是节点为空时。我的猜测是在这种情况下,返回值的寄存器将包含数据数组。在函数末尾进行递归函数调用时,数据数组的地址将保留在寄存器中并向前传输 - 但您不能指望这一点,如果您想使用它,您需要实际返回地址

【讨论】:

  • 我应该如何修改我的代码以返回地址,而不破坏一切?
  • @Uclydde 您可以在函数末尾添加 return dataArray - 但我相信最好将函数修改为 void 并在 main 中使用原始数组
  • 添加 return 语句成功了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-09
  • 2014-08-26
相关资源
最近更新 更多