PAT-A 1119 Pre- and Post-order Traversals (30 分)

假设一个二叉树上所有结点的权值都互不相同。

我们可以通过后序遍历和中序遍历来确定唯一二叉树。

也可以通过前序遍历和中序遍历来确定唯一二叉树。

但是,如果只通过前序遍历和后序遍历,则有可能无法确定唯一二叉树。

现在,给定一组前序遍历和后序遍历,请你输出对应二叉树的中序遍历。

如果树不是唯一的,则输出任意一种可能树的中序遍历即可。

输入格式
第一行包含整数 N,表示结点数量。

第二行给出前序遍历序列。

第三行给出后序遍历序列。

一行中的数字都用空格隔开。

输出格式
首先第一行,如果树唯一,则输出 Yes,如果不唯一,则输出 No。

然后在第二行,输出树的中序遍历。

注意,如果树不唯一,则输出任意一种可能的情况均可。

数据范围
1≤N≤30
输入样例1:
7
1 2 3 4 6 7 5
2 6 7 4 5 3 1
输出样例1:
Yes
2 1 6 4 7 3 5
输入样例2:
4
1 2 3 4
2 4 3 1
输出样例2:
No
2 1 3 4

依旧是建树

#include <bits/stdc++.h>

using namespace std;
int pre[1010],post[1010];
struct node
{
    int data;
    struct node*l,*r;
};
int n;
bool is=true;
int num;
void zhongxv(struct node*root)
{
    if(root)
    {
        zhongxv(root->l);
        num++;
        cout <<root->data;
        if(num!=n)
        cout <<" ";
        zhongxv(root->r);
    }
}
struct node*create(int h1,int h2,int len)
{
    if(len==0)
    return NULL;
    struct node*p ;
    p = new node;
    p->data=pre[h1];
   // cout <<pre[h1]<<endl;
    if(len==1)
    return p;
    int i;
    for( i=h2;post[i]!=pre[h1+1];i++);
    int l1 = i-h2+1;
    int l2 = len-1-l1;
    if(l2 == 0)
    is=false;
    p->l = create(h1+1,h2,l1);
    p->r = create(h1+l1+1,i+1,l2);
    return p;
}
int main()
{
    cin >> n;
    for(int i=1;i<=n;i++)
    cin >>pre[i];
    for(int i=1;i<=n;i++)
    cin >>post[i];
    struct node*root;
    root=create(1,1,n);
    if(is==true)
    cout <<"Yes"<<endl;
    else
    cout <<"No"<<endl;
    zhongxv(root);
    cout <<endl;
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值