欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

105. Construct Binary Tree from Preorder and Inorder Traversal

程序员文章站 2022-03-03 10:12:35
...

我觉得我自己的递归写的还是非常不熟悉,这道题本应该是很简单的。。。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

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