PAT-A 1138 Postorder Traversal (25 分)

假设二叉树上各结点的权值互不相同且都为正整数。

给定二叉树的前序遍历和中序遍历,请你输出二叉树的后序遍历的第一个数字。

输入格式
第一行包含整数 N,表示二叉树结点总数。

第二行给出二叉树的前序遍历序列。

第三行给出二叉树的中序遍历序列。

输出格式
输出二叉树的后序遍历的第一个数字。

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

数据量略大,用了unordered_map来去减少pre与inorder的匹配时间。

#include <bits/stdc++.h>

using namespace std;
int n;
unordered_map<int,int> mp;
int pre[50010],inorder[51010];
struct node
{
    int data;
    struct node*l,*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];
   int  i = mp[pre[h1]];
    int l1 = i-h2;
    int l2 = len-l1-1;
    p->l = create(h1+1,h2,l1);
    p->r = create(h1+l1+1,i+1,l2);
    return p;
};
void houxv(struct node*root)
{
    if(root)
    {
        houxv(root->l);
        houxv(root->r);
        cout <<root->data;
        exit(0);
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin >> n;
    for(int i=1;i<=n;i++)
    cin >>pre[i];
    for(int i=1;i<=n;i++)
    {
        cin >>inorder[i];
        mp[inorder[i]] = i;
    }
    
    struct node*root ;
    root= create(1,1,n);
  houxv(root);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值