1138 Postorder Traversal (25)

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 (<=50000), 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
由前序,中序找后序,固定的套路,自己递归几次就能明白;
因为只需要输出后序遍历的第一个元素, 所以在递归得到第一个元素的时候就退退出, 避免不必要的时空浪费

 

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 bool flag=true; //表示是否找到后序遍历的第一个元素
 5 vector<int> pre, in;
 6 void postOrder(int prel, int inl, int inr){
 7   int i=inl;
 8   if(inl>inr || !flag) return;
 9   while(in[i]!=pre[prel]) i++;
10   postOrder(prel+1, inl, i-1);
11   postOrder(prel+1+i-inl, i+1, inr);
12   if(flag){
13     printf("%d", pre[prel]);
14     flag=false;
15   }
16 }
17 int main(){
18   int n, i;
19   scanf("%d", &n);
20   pre.resize(n); in.resize(n);
21   for(i=0; i<n; i++) scanf("%d", &pre[i]);
22   for(i=0; i<n; i++) scanf("%d", &in[i]);
23   postOrder(0, 0, n-1);
24   return 0;
25 }

 

posted @ 2018-06-05 22:47  赖兴宇  阅读(141)  评论(0编辑  收藏  举报