PAT 1020 Tree Traversals (25)

Posted mr-stn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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, int inl, 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)的主要内容,如果未能解决你的问题,请参考以下文章

PAT1020: Tree Traversals

PAT 1020 Tree Traversals (25)

PAT_A1020#Tree Traversals

PAT 甲级 1020 Tree Traversals

PAT1020 Tree Traversals (25)(25 分)

PAT Advanced 1020 Tree Traversals (25分)