leetcode_106 从中序与后序遍历序列构造二叉树

77 阅读1分钟

要求

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

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

例如,给出

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

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

核心代码

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
        
class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        if not postorder:
            return None
        root = TreeNode(postorder[-1])
        root_index = inorder.index(root.val)
        left_inorder = inorder[:root_index]
        right_inorder = inorder[root_index + 1:]

        l_left = len(left_inorder)
        left_postorder = postorder[:l_left]
        right_postorder = postorder[l_left:-1]
        root.left = self.buildTree(left_inorder,left_postorder)
        root.right = self.buildTree(right_inorder,right_postorder)
        return root

image.png

解题思路:这个题和105通过前序序列和中序序列还原二叉树的思路是一样的,后续遍历实际上根在后面,还是要找到左子树和右子树的划分边界,最终递归构建整个的二叉树。