假设二叉树上各结点的权值互不相同且都为正整数。
给定二叉树的前序遍历和中序遍历,请你输出二叉树的后序遍历的第一个数字。
输入格式
第一行包含整数 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 = 50010;
int n;
int pre[N], in[N];
unordered_map<int, int> pos;
int post;
void build(int il, int ir, int pl, int pr)
{
int root = pre[pl];
int k = pos[root];
if (il < k) build(il, k - 1, pl + 1, pl + 1 + k - 1 - il);
if (ir > k) build(k + 1, ir, pl + 1 + k - 1 - il + 1, pr);
if (!post) post = root;
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ ) cin >> pre[i];
for (int i = 0; i < n; i ++ )
{
cin >> in[i];
pos[in[i]] = i;
}
build(0, n - 1, 0, n - 1);
cout << post << endl;
return 0;
}