首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >预顺序树遍历工作,但postorder不工作

预顺序树遍历工作,但postorder不工作
EN

Stack Overflow用户
提问于 2018-11-11 16:41:51
回答 1查看 85关注 0票数 1

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

但是,我的postorder函数不能工作。当函数被调用时,我会得到一个分段错误。

当编译和运行下面的代码时,但是在调用postorder方法之后,我会得到一个分段错误。

这是我的密码:

代码语言:javascript
复制
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;
    }
  }
}

打电话时:

代码语言:javascript
复制
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循环的原因)

有什么问题吗?我的邮件和预订有什么不同?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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循环应该如下:

代码语言:javascript
复制
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时。我猜在这种情况下,返回值的寄存器将包含数据数组。当递归函数调用位于函数的末尾时,数据数组的地址停留在寄存器中并向前传输--但是您不能指望它,如果要使用它,就需要实际返回地址。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53250899

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档