A1127 ZigZagging on a Tree (30 point(s))

中序+后序=层序

1. 原文

Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences. And it is a simple standard routine to print the numbers in level-order. However, if you think the problem is too simple, then you are too naive. This time you are supposed to print the numbers in “zigzagging order” – that is, starting from the root, print the numbers level-by-level, alternating between left to right and right to left. For example, for the following tree you must output: 1 11 5 8 17 12 20 15.

zigzag.jpg

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 inorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.

output Specification:

For each test case, print the zigzagging sequence of the tree in a line. 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
8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1

Sample output:

1
1 11 5 8 17 12 20 15

2. 解析

中序 左 根 右

后序 左 右 根

1
getLevel(int inl,int inr,int postr,int deep) 
1
level[deep].push_back(post[postr])

每层递归添加

最终层按奇偶数输出

1
2
3
4
5
6
 printf("%d", level[1][0]);
for (int i = 2; i <= maxdeep; ++i)
{
if (i%2==0){}
else{}
}

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
60
61
#include<cstdio>
#include<vector>
using namespace std;
int in[40]={};
int post[40]={};
int maxdeep=-1;
vector<int> level[40];
void getLevel(int inl,int inr,int postr,int deep){
if (deep>maxdeep)
{
maxdeep=deep;
}
if (inl>inr)
{
return;
}
level[deep].push_back(post[postr]);
int i=0;
for (i = inl; i <= inr; ++i)
{
if (in[i]==post[postr])
{
break;
}
}
getLevel(inl,i-1,postr-(inr-i)-1,deep+1);
getLevel(i+1,inr,postr-1,deep+1);

}
int main()
{
int n;
scanf("%d",&n);
for (int i = 0; i < n; ++i)
{
scanf("%d",&in[i]);
}
for (int i = 0; i < n; ++i)
{
scanf("%d",&post[i]);
}
getLevel(0,n-1,n-1,1);

printf("%d", level[1][0]);
for (int i = 2; i <= maxdeep; ++i)
{
if (i%2==0)
{
for (int j = 0; j < level[i].size(); ++j)
{
printf(" %d",level[i][j]);
}
}else{
for (int j = level[i].size()-1; j >=0 ; j--)
{
printf(" %d",level[i][j]);
}
}
}
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1127/
  • 发布时间: 2019-09-03 08:34
  • 更新时间: 2021-10-29 14:09
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!