PAT 1020 Tree Traversals (25)
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.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), 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.
Output Specification:
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.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
題目大意:通過後序遍歷和中序遍歷,輸出層序遍歷
註意點:層序遍歷的時候,添加到隊列中的是結點序號,而不是結點的值, 壓入層序遍歷結果的才是結點的值
1 #include<iostream> 2 #include<vector> 3 #include<queue> 4 using namespace std; 5 vector<int> post(30), in(30), level; 6 int tree[30][2]; 7 int root; 8 9 void dfs(int &index, intinl, int inr, int postl, int postr){ 10 if(inl>inr) return ; 11 index = postr; 12 int temp=post[postr], i=inl; 13 while(i<=inr && in[i]!=temp) i++; 14 dfs(tree[index][0], inl, i-1, postl, postl+(i-inl)-1); 15 dfs(tree[index][1], i+1, inr, postl+i-inl, postr-1); 16 } 17 18 void bfs(){ 19 queue<int> q; 20 q.push(root); 21 while(q.size()){ 22 int temp=q.front(); 23 q.pop(); 24 level.push_back(post[temp]); 25 if(tree[temp][0]!=-1) q.push(tree[temp][0]); 26 if(tree[temp][1]!=-1) q.push(tree[temp][1]); 27 } 28 } 29 int main(){ 30 int n, i; 31 cin>>n; 32 fill(tree[0], tree[0]+60, -1); 33 for(i=0; i<n; i++) cin>>post[i]; 34 for(i=0; i<n; i++) cin>>in[i]; 35 dfs(root, 0, n-1, 0, n-1); 36 bfs(); 37 cout<<level[0]; 38 for(i=1; i<n; i++) cout<<" "<<level[i]; 39 return 0; 40 }
PAT 1020 Tree Traversals (25)