【python】给定一个二叉树的前序遍历和中序遍历的序列,输出对应这个二叉树的后续遍历序列。

题目链接:https://www.nowcoder.com/question/next?pid=6663034&qid=116495&tid=26408801

思路和《剑指offer》的“重建二叉树”一样

tree = input().split(' ')
pre = tree[0]
tin = tree[1]
aftree = []

def reConstruction(aftree,pre,tin):
    if len(pre) == 0:
        return None
    if len(pre) == 1:
        return pre[0]
    aftree.append(pre[0])
    i = 0
    for i in range(len(tin)):
        if tin[i] == pre[0]:
            break
    left_pre = pre[1:1+i]
    right_pre = pre[1+i:]
    left_tin = tin[:i]
    right_tin = tin[i+1:]
    aftree.append(reConstruction(aftree,right_pre,right_tin))
    aftree.append(reConstruction(aftree,left_pre,left_tin))

reConstruction(aftree,pre,tin)
tmp = []
for i in aftree:
    if i != None:
        tmp.append(i)
res = ''.join(tmp)
print(res[::-1])

 

你可能感兴趣的:(剑指offer)