美文网首页
105. Construct Binary Tree from

105. Construct Binary Tree from

作者: 阿团相信梦想都能实现 | 来源:发表于2016-12-11 15:59 被阅读0次
# 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
        """
        def buildTree(i_start,i_end,p_start,p_end):
            if i_start==i_end:return None
            root=TreeNode(preorder[p_start])
            r_idx=inorder[i_start:i_end].index(root.val)
            root.left=buildTree(i_start,i_start+r_idx,p_start+1,p_start+1+r_idx)
            root.right=buildTree(i_start+r_idx+1,i_end,p_start+r_idx+1,p_end)
            return root
        if not preorder or not inorder:return None
        return buildTree(0,len(inorder),0,len(preorder))

相关文章

网友评论

      本文标题:105. Construct Binary Tree from

      本文链接:https://www.haomeiwen.com/subject/pwdpmttx.html