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.
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:
8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1
1
2
3
4
8
1211201711585
1220171115851
Sample Output:
1 11 5 8 17 12 20 15
1
1115817122015
题目大意
给定一棵树的节点数以及中序遍历和后序遍历,要求输出这个树的”Z”型层序遍历。
分析
使用数组midd存储这颗树的中序遍历,使用数组post存储这颗树的后序遍历。使用bfs(midd, post)函数来层序遍历这颗树。
每次bfs函数获取post数组的最后一个元素,这个元素是这一段二叉树片段的根节点。在midd数组中找到根节点的位置,左边是左子树,右边是右子树。判断序列不为空则加入temp数组留待下一次层序遍历使用。将二叉树片段的根节点保存在now数组中,在while循环中判断当前是奇数层还是偶数层(从0开始)。偶数层反转now数组,奇数层不反转。将now数组加入result数组。继续下一次的层序遍历。
最后输出result数组即可
Python实现
Python实现
Python
def bfs(midd, post):
global result, temp, now
now.append(post[-1])
index = midd.index(post[-1])
if len(post[:index]) > 0:
temp.append([midd[:index], post[:index]])
if len(post[index:-1]) > 0:
temp.append([midd[index+1:], post[index:-1]])
if __name__ == "__main__":
num = int(input())
line = input().split(" ")
midd = [int(x) for x in line]
line = input().split(" ")
post = [int(x) for x in line]
result = []
a = [[midd, post]]
count = 0
while(len(a) > 0):
temp = []
now = []
for x in a:
bfs(x[0], x[1])
if count % 2 == 0:
result += now[::-1]
else:
result += now
count += 1
a = temp
result = [str(x) for x in result]
print(" ".join(result))
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
defbfs(midd,post):
globalresult,temp,now
now.append(post[-1])
index=midd.index(post[-1])
iflen(post[:index])>0:
temp.append([midd[:index],post[:index]])
iflen(post[index:-1])>0:
temp.append([midd[index+1:],post[index:-1]])
if__name__=="__main__":
num=int(input())
line=input().split(" ")
midd=[int(x)forxinline]
line=input().split(" ")
post=[int(x)forxinline]
result=[]
a=[[midd,post]]
count=0
while(len(a)>0):
temp=[]
now=[]
forxina:
bfs(x[0],x[1])
ifcount%2==0:
result+=now[::-1]
else:
result+=now
count+=1
a=temp
result=[str(x)forxinresult]
print(" ".join(result))