后序遍历

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

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

输入格式

第一行包含整数 NN,表示二叉树结点总数。

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

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

输出格式

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

数据范围

1≤N≤500001≤N≤50000

输入样例:
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
输出样例:
3
#include <iostream>
#include <unordered_map>
using namespace std;
const int N=5e4+10;
int cnt,res[N];
unordered_map<int,int >l,r,pos;
int preorder[N],inorder[N];
int build(int pl,int pr,int il,int ir)
{
    if(pl>pr)    return 0;
    int root=preorder[pl]; 
    int k=pos[root];
    if(il<k)  l[root]=  build(pl+1,pl+k-il,il,k-1);
    if(ir>k)   r[root]= build(pl+k-il+1,pr,k+1,ir);
 
    return root;
}
void dfs(int u )
{
    
    if(l[u])    dfs(l[u]);
    if(r[u])    dfs(r[u]);
    res[cnt++]=u;
     
    if(cnt>=1)    return ;
}
int main()
{
    int  n;
    cin>>n;
    for(int i=0;i<n;i++)    cin>>preorder[i];
    for(int i=0;i<n;i++)    cin>>inorder[i],pos[inorder[i]]=i;
    int root=build(0,n-1,0,n-1);
    dfs(root);
    cout<<res[0];
}

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值