【问题标题】:printing postorder from given inorder and preorder从给定的顺序和预购打印后购
【发布时间】:2020-06-21 00:48:29
【问题描述】:

以下用于从给定的 preorder 和 inorder 打印 postorder 的代码显示分段错误。你能解释一下为什么吗??

int j=0;
void post_order(int in[],int pre[],int start,int end){
    if(start>end) {
        return;
    }
    int i;
    for(int i=start;i<=end;i++){
        if(pre[j]==in[i]){
            break;
        }
    }

    j++;
    post_order(in,pre,start,i-1);
    post_order(in,pre,i+1,end);
    cout<<in[i]<<" ";
}
void printPostOrder(int in[], int pre[], int n)
{
//Your code here
int start=0;
int end = n-1;
post_order(in,pre,start,end);

}

【问题讨论】:

  • 请提供minimal reproducible example,包括演示问题的示例输入。
  • 您已经获得了两个数组,一个代表树的前序和其他中序遍历,如图所示: preorder_array: 1 2 4 5 3 6 inorder_array: 4 2 5 1 3 6
  • 我不明白你评论的重点。考虑edit您添加信息的问题,而不是将其隐藏在 cmets 中。

标签: c++ arrays recursion binary-tree


【解决方案1】:
    int i;  //< uninitialised

    //   V--- a new variable called 'i'
    for(int i=start;i<=end;i++){
        if(pre[j]==in[i]){
            break;
        }
    }


    // this will probably crash (i hasn't been initialised yet!)
    cout<<in[i]<<" ";

【讨论】:

  • 所以如果我用 say i=start 初始化 i 会显示正确的结果吗??
  • for(i=start;i
  • 仍然出现分段错误
猜你喜欢
  • 1970-01-01
  • 2012-09-21
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
  • 2015-03-19
相关资源
最近更新 更多