由前序遍历和中序遍历构造二叉树

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

 返回如下:

    3
   / \
  9  20
    /  \
   15   7

前序第一个必为根节点,而在中序遍历中位于此节点左边的是它的左子树,右边的是右子树。而在前序遍历中,左右子树连续的排列在根节点后。于是可用递归解此题。

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        def build(preleft,preright,inoleft,inoright):
            if preleft >preright:
                return None
            
            preroot = preleft
            inoroot = inorder.index(preorder[preroot])
            size = inoroot - inoleft
            root = TreeNode(preorder[preroot])

            root.left = build(preleft+1,preleft+size,inoleft,inoroot-1)
            root.right = build(preleft+size+1,preright,inoroot+1,inoright)

            return root
        n = len(preorder)
        return build(0,n-1,0,n-1)

 

上一篇:二叉树的前序遍历


下一篇:[LeetCode] 889. Construct Binary Tree from Preorder and Postorder Traversal