A1020 Tree Traversals (25 point(s))

后+中=层

1. 原文

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:

1
2
3
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample output:

1
4 1 6 3 5 7 2

2. 解析

后+˙中 = 层

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
int in[40],post[40];
struct node{
int index,data;
node(int x,int y){
index=x;
data=y;
}
};
vector<node> level;
bool cmp(node a,node b){
return a.index<b.index;
}
void levelOrder(int root,int inl,int inr,int index){
if (inl>inr)
{
return;
}
int i = inl;
for (; i <= inr; ++i){
if (post[root]==in[i])
{
break;
}
}
int right = inr-i;
level.push_back(node(index,post[root]));
levelOrder(root-1-right,inl,i-1,2*index+1);
levelOrder(root-1,i+1,inr,2*index+2);
}
int main(){
int n;
scanf("%d",&n);
for (int i = 0; i < n; ++i)
{
scanf("%d",&post[i]);
}
for (int i = 0; i < n; ++i)
{
scanf("%d",&in[i]);
}
levelOrder(n-1,0,n-1,0);
sort(level.begin(),level.end(),cmp);
for (int i = 0; i < n; ++i)
{
printf("%d",level[i].data);
if (i<n-1)
{
printf(" ");
}else{
printf("\n");
}
}

return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1020/
  • 发布时间: 2019-09-03 12:35
  • 更新时间: 2021-10-29 13:59
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!