← 返回题库
初级

Tree Traversals

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
def solve(postorder, inorder):
    postorder = list(map(int, postorder.split(",")))
    inorder = list(map(int, inorder.split(",")))
    def build(post, ino):
        if not post:
            return None
        root = post[-1]
        idx = ino.index(root)
        return (root, build(post[:idx], ino[:idx]), build(post[idx:-1], ino[idx+1:]))
    tree = build(postorder, inorder)
    from collections import deque
    q = deque([tree])
    result = []
    while q:
        nd = q.popleft()
        if nd:
            result.append(nd[0])
            q.append(nd[1])
            q.append(nd[2])
    print(" ".join(map(str, result)))

示例

输入
solve('2,3,1,5,7,6,4', '1,2,3,4,5,6,7')
期望输出
4 1 6 3 5 7 2
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码