# PAT-A 真题 – 1138 Postorder Traversal

Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder traversal sequence of the corresponding binary tree.

### Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N ( 50,000), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

### Output Specification:

For each test case, print in one line the first number of the postorder traversal sequence of the corresponding binary tree.

### Sample Input:

7
1 2 3 4 5 6 7
2 3 1 5 4 7 6

### Sample Output:

3

#include <bits/stdc++.h>
using namespace std;
unordered_map<int, int> mp;
vector<int> pre, in;

int get(int preL, int preR, int inL, int inR){
if(preL == preR) return pre[preL];
if(pre[preL] == in[inL])  //没有左子树
return get(preL + 1, preR, inL + 1, inR);  //找右子树
int root = pre[preL], lchild_len = mp[root] - inL;
return get(preL + 1, preL + lchild_len, inL, inL + lchild_len - 1);  //找左子树
}

int main(){
int cnt;
cin >> cnt;
pre.resize(cnt), in.resize(cnt);
for(int & i : pre) cin >> i;
for(int i = 0; i < cnt; i++){
cin >> in[i];
mp[in[i]] = i;
}
cout << get(0, cnt-1, 0, cnt-1) << endl;
return 0;
}