PAT_A1138#Postorder Traversal
Source:
Description:
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
Keys:
- 二叉树的遍历
Attention:
- 建树的过程实质上也是遍历二叉树的过程
Code:
1 /* 2 Data: 2019-05-26 20:53:20 3 Problem: PAT_A1138#Postorder Traversal 4 AC: 16:20 5 6 题目大意: 7 假设二叉树中各个结点权值不同且为正; 8 给出先序和中序遍历,求后序遍历中的第一个结点 9 */ 10 11 #include<cstdio> 12 const int M=1e5; 13 int pre[M],in[M],f=1; 14 15 void Travel(int preL, int preR, int inL, int inR) 16 { 17 if(preL > preR) 18 return; 19 int k; 20 for(k=inL; k<=inR; k++) 21 if(in[k]==pre[preL]) 22 break; 23 int numLeft = k-inL; 24 Travel(preL+1, preL+numLeft, inL,k-1); 25 Travel(preL+numLeft+1, preR, k+1,inR); 26 if(f){ 27 printf("%d\n", in[k]);f=0; 28 } 29 } 30 31 int main() 32 { 33 #ifdef ONLINE_JUDGE 34 #else 35 freopen("Test.txt", "r", stdin); 36 #endif 37 38 int n; 39 scanf("%d", &n); 40 for(int i=0; i<n; i++) 41 scanf("%d", &pre[i]); 42 for(int i=0; i<n; i++) 43 scanf("%d", &in[i]); 44 Travel(0,n-1,0,n-1); 45 46 return 0; 47 }