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 (≤ 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
思路:
这个题目要求输出后序遍历第一个元素,所以只需要进行分割和输出即可。为了尽快推出递归,增加flag变量;
为了加快速度,使用了哈希,这样在分割序列的时候不需要再进行循环。
#include<iostream> #include<vector> #include<algorithm> #include<queue> #include<string> #include<map> #include<set> #include<stack> #include<string.h> #include<cstdio> #include<cmath> using namespace std; int pre[50001]; int in[50001]; map<int,int>mp; bool flag=true; void createTree(int pl,int pr,int il,int ir) { if(!flag) return; int index=mp[pre[pl]]; int len=index-il; int rlen=ir-index; if(len>0) createTree(pl+1,pl+len,il,index-1); if(rlen>0) createTree(pl+len+1,pr,index+1,ir); if(flag) { printf("%d",pre[pl]); // cout<<pre[pl]; flag=false; return; } } int main() { int n; scanf("%d",&n); for(int i=0; i<n; i++) scanf("%d",&pre[i]); //cin>>pre[i]; for(int i=0; i<n; i++) { scanf("%d",&in[i]); mp[in[i]]=i; } //cin>>in[i]; createTree(0,n-1,0,n-1); // non_recur(root); //stack<Node*> st; return 0; }