假设二叉树上各结点的权值互不相同且都为正整数。
给定二叉树的前序遍历和中序遍历,请你输出二叉树的后序遍历的第一个数字。
输入格式
第一行包含整数 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;
}