标签:cat ica std round col bin case tin justify
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Each input file contains one test case. For each case, the first line gives a positive integer N (≤), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
4 1 6 3 5 7 2
这道题考察了中序后序建树,然后层序遍历。
实际上,我们在进行递归的时候进行建一个索引,之后用map进行保存即可
#include <iostream> #include <map> using namespace std; int N; int post[100],in[100]; map<int,int> m; /** root是post的索引,而start和_end都是为了确定in的索引*/ void pre(int root,int start,int _end,int index){ if(start>_end) return; int i=start; while(i<_end&&in[i]!=post[root]) i++; m[index]=post[root]; pre(root-(_end-i)-1,start,i-1,index*2); pre(root-1,i+1,_end,index*2+1); } int main(){ cin>>N; for(int i=1;i<=N;i++) cin>>post[i]; for(int i=1;i<=N;i++) cin>>in[i]; pre(N,1,N,1); bool start = true; for(auto it=m.begin();it!=m.end();it++) if(start) start=false,printf("%d",it->second); else printf(" %d",it->second); system("pause"); return 0; }
PAT Advanced 1020 Tree Traversals (25分)
标签:cat ica std round col bin case tin justify
原文地址:https://www.cnblogs.com/littlepage/p/12219182.html