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
AC代码
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
int n, pre[50010], in[50010];
bool flag = false; //第一个数字是否输出
void postorder(int l1, int h1, int l2, int h2){
if(flag == true || l2 > h2) return;
int k = l2; //找到中序序列中根结点的位置
while(in[k] != pre[l1]) k++;
int num = l2 - k; //左子树上的结点数量
postorder(l1 + 1, l1 + num, l2, k - 1);
postorder(l1 + num + 1, h1, k + 1, h2);
if(flag == false){
cout<<in[k];
flag = true;
}
}
int main(){
cin>>n;
for(int i = 0; i < n; i++)
cin>>pre[i];
for(int i = 0; i < n; i++)
cin>>in[i];
postorder(0, n - 1, 0, n - 1);
return 0;
}