二叉树 | 根据前序、后序生成中序

OJ链接:https://www.patest.cn/contests/pat-a-practise/1119

我的分析过程:pat1119分析.pdf

 参考博客:https://www.cnblogs.com/xiongmao-cpp/p/6498672.html


 

实现代码:

//caution: should using initialize code: " t=0; "
void setIn(int preS,int preE,int postS,int postE){
    if(preS==preE){
        in[t++]=pre[preS];
        return;
    }
    //finding the elem which is the root of left sub_tree
    int i=postS;
    while(i<=postE && post[i]!=pre[preS+1]) i++;
    //calculate the numbers of left sub_tree
    int leftNum=i-postS+1;
    //is paradox
    if(i==postE-1){
        flag=0;
        setIn(preS+1,preS+leftNum,postS,i);//default consider this is a right leaf
        in[t++]=pre[preS];
        return;
    }
    //build the in_order traversal sequence
    setIn(preS+1,preS+leftNum,postS,i);
    in[t++]=pre[preS];
    setIn(preS+leftNum+1,preE,i+1,postE-1);
}

 

完整代码:

#include <stdio.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <map>


#define I scanf
#define OL puts
#define O printf
#define F(a,b,c) for(a=b;a<c;a++)
#define FF(a,b) for(a=0;a<b;a++)
#define FG(a,b) for(a=b-1;a>=0;a--)
#define LEN 10000
#define MAX 0x06FFFFFF
#define V vector<int>

using namespace std;

int in[LEN];
int pre[LEN];
int post[LEN];
int t=0;
int flag=1;

//caution: should using initialize code: " t=0; "
void setIn(int preS,int preE,int postS,int postE){
    if(preS==preE){
        in[t++]=pre[preS];
        return;
    }
    //finding the elem which is the root of left sub_tree
    int i=postS;
    while(i<=postE && post[i]!=pre[preS+1]) i++;
    //calculate the numbers of left sub_tree
    int leftNum=i-postS+1;
    //is paradox
    if(i==postE-1){
        flag=0;
        setIn(preS+1,preS+leftNum,postS,i);//default consider this is a right leaf
        in[t++]=pre[preS];
        return;
    }
    //build the in_order traversal sequence
    setIn(preS+1,preS+leftNum,postS,i);
    in[t++]=pre[preS];
    setIn(preS+leftNum+1,preE,i+1,postE-1);
}

int main(){
//    freopen("d:/input/A1119_2.txt","r",stdin);
    int n,i;
    scanf("%d",&n);
    FF(i,n) scanf("%d",&pre[i]);
    FF(i,n) scanf("%d",&post[i]);
    setIn(0,n-1,0,n-1);
    puts(flag?"Yes":"No");
    FF(i,n){
        O("%d",in[i]);
        if(i!=n-1)O(" ");
    }
    puts("");
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/TQCAI/p/8404575.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值