105. 从前序与中序遍历序列构造二叉树

https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

解法一:递归

易知前序的第0号元素为树的根,在中序里找这个根,然后以该根为界将中序数组划分成左右两半,依次递归进行。难点在于每次还要根据中序的划分来将前序数组也划分。

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if len(preorder) == 0 or len(inorder) == 0:
            return
        root = TreeNode(preorder[0])
        mid = inorder.index(preorder[0])
        #以mid为界划分中序
        in_l = inorder[:mid]
        in_r = inorder[mid+1:]
        #根据中序划分前序
        pre_l = preorder[1:1+len(in_l)]
        pre_r = preorder[1+len(in_l):]
        #递归构造左右子树
        root.left = self.buildTree(pre_l, in_l)
        root.right = self.buildTree(pre_r, in_r)
        return root

最后更新于