链接
https://pintia.cn/problem-sets/994805342720868352/problems/994805485033603072
题解
这题就是告诉你后序遍历和中序遍历,让你输出层序遍历(就是像
B
F
S
BFS
BFS那样按深度递增便利)
根据后序遍历,我可以直接确定根,然后在中序遍历的序列中找到根,根的左侧就是左子树,右侧就是右子树,左右子树在遍历序列中所占的区间也是一样的范围
递归下去
代码
def work(list1,list2,deepth):
root = list1[-1]
c[deepth].append(root)
mid = list2.index(root)
if mid!=0:
work(list1[:mid],list2[:mid],deepth+1)
if mid!=len(list2)-1:
work(list1[mid:-1],list2[mid+1:],deepth+1)
n = int(input())
postorder = [int(x) for x in input().split()]
inorder = [int(x) for x in input().split()]
c=[]
for i in range(n+10): c.append([])
work(postorder,inorder,0)
i=0
while(len(c[i+1])>0):
print(*c[i],end=' ')
i=i+1
print(*c[i])