PAT 1020. Tree Traversals

题目的意思,是要根据一个二元树的后序遍历序列(post order)和它的中序遍历序列(inorder),来求得此树的层遍历序列。

核心思想,是根据后序遍历序列中最后出现的一个数字,一定是这些节点的根节点。而根据此根节点,可以在中序遍历中把树分为左子树和右子树,再递归调用方法即可。

为了按层输出,首先把每个层上的节点存储起来,最后在输出

Python代码:


N=int(raw_input())
post_odr=[int(x) for x in raw_input().split()][::-1]  #输入后序遍历,并且做倒序处理
in_odr=[int(x) for x in raw_input().split()]  #输入中序遍历




def find_first(Q):   #找到一个节点集合中,最早出现的节点,此节点即为根节点
	for it in post_odr:
		for j in range(0,len(Q)):
			if it==Q[j]:
				return (it,j)

level=0
res={}   #为了按层输出,首先把每个层上的节点存储起来
def f(Q):
	global level
	if len(Q)==0:
		return
	if len(Q)==1:
		if not res.has_key(level):  res[level]=[] #为了按层输出,首先把每个层上的节点存储起来
		res[level].append(Q[0])
		return
	(first,index)=find_first(Q)
	if not res.has_key(level):
			res[level]=[]  #为了按层输出,首先把每个层上的节点存储起来
	res[level].append(first)
	Q1=[]
	Q2=[]
	if index!=0:#把中序遍历分为两个结合
		Q1=Q[:index]
	if index<len(Q)-1:
		Q2=Q[index+1:]
	level=level+1 #层数
	f(Q1) #左子树
	f(Q2) #右子树
	level=level-1

f(in_odr) #调用函数
for key in res.keys(): #最后输出
	for it in res[key]:
		print it,


你可能感兴趣的:(tree,pat,Traversals,1020.)