PAT (Advanced Level) Practice A1119 Pre- and Post-order Traversals (30 分)(已知前序、后序求中序)

原题链接

#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

const int MAX = 50, INF = 1<<30;

typedef struct BiTNode
{
    int data, height;
    struct BiTNode *lChild, *rChild;
}BiTNode, *BiTree;

int Pre[MAX], Post[MAX], In[MAX];
int N, cnt = 0;
bool flag = 0;

void getIn(int preL, int preR, int postL, int postR)
{
    if(preL == preR)
    {
        In[cnt++] = Pre[preL];
        return ;
    }
    int k = preL+1;
    while(k <= preR && Pre[k] != Post[postR-1]) k++;
    if(k > preR) return ;
    if(k - preL > 1) getIn(preL+1, k-1, postL, postL+k-preL-2);
    else flag = 1;//此时该节点放在当前节点的左右子树都可以,这里放在了右子树
    In[cnt++] = Pre[preL];//按中序存储
    getIn(k, preR, postL+k-preL-1, postR-1);
}

int main()
{
    scanf("%d", &N);
    for(int i=0; i<N; i++) scanf("%d", &Pre[i]);
    for(int i=0; i<N; i++) scanf("%d", &Post[i]);
    getIn(0, N-1, 0, N-1);
    if(flag) printf("No\n");
    else printf("Yes\n");
    printf("%d", In[0]);
    for(int i=1; i<cnt; i++) printf(" %d", In[i]);
    printf("\n");//头一次遇见最后没回车报格式错误的……
	return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值