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:
#include<iostream> #include<vector> using namespace std; bool flag=true; vector<int> ans; void dfs(vector<int> pre,vector<int> in,int prel,int inl,int inr){ int i=inl; if(inl>inr) return; while(in[i]!=pre[prel]&&i<inr) i++; dfs(pre,in,prel+1,inl,i-1); dfs(pre,prel+1+i-inl,i+1,inr); ans.push_back(pre[prel]); } int main(){ int n,i; cin>>n; vector<int> pre(n),in(n); for(i=0; i<n; i++) cin>>pre[i]; for(i=0; i<n; i++) cin>>in[i]; dfs(pre,0,n-1); cout<<ans[0]<<endl; return 0; } #include<iostream> #include<vector> using namespace std; bool flag=true; vector<int> ans; void dfs(vector<int> pre,int inr){ int i=inl; if(inl>inr || !flag) return; while(in[i]!=pre[prel]&&i<inr) i++; dfs(pre,inr); if(flag){ cout<<pre[prel]; flag=false; } } int main(){ int n,in(n); for(i=0; i<n; i++) scanf("%d",&pre[i]); for(i=0; i<n; i++) scanf("%d ",&in[i]); dfs(pre,n-1); return 0; } #include<iostream> #include<vector> using namespace std; bool flag=true; vector<int> ans; void dfs(vector<int> &pre,vector<int> &in,int inr){ int i=inl; if(inl>inr || !flag) return; while(in[i]!=pre[prel]) i++; dfs(pre,n-1); return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |