106 - 从中序与后序遍历序列构造二叉树 - python

47 阅读1分钟

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

这道题和105 - 从前序与中序遍历序列构造二叉树 - python道理是一样的,我们只需要找出左子树和右子树分别对应前序遍历序列和中序遍历序列即可。


在这里插入图片描述

AC code:

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        if len(postorder) == 0: return None
        if len(postorder) == 1:
            return TreeNode(postorder[-1])
        else:
            root = TreeNode(postorder[-1])
            index = inorder.index(root.val)

            root.left = self.buildTree(inorder[:index], postorder[: index])
            root.right = self.buildTree(inorder[index + 1:], postorder[index: -1])

            return root