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

思路:递归

class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        if len(preorder) == 0:
            return None
        root = TreeNode(preorder[0])
        root_index = inorder.index(preorder[0])
        root.left = Solution().buildTree(preorder[1:1+root_index],inorder[:root_index])
        root.right = Solution().buildTree(preorder[1+root_index:],inorder[root_index+1:])
        return root

你可能感兴趣的:(105.从前序遍历和中序遍历序列构造二叉树)