美文网首页
106. Construct Binary Tree from

106. Construct Binary Tree from

作者: 阿团相信梦想都能实现 | 来源:发表于2016-12-11 15:49 被阅读0次
recursive solution.
the last element in the postorder array is always the root 
pass index instead of array to save memory 
# 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, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        def buildTree(i_start,i_end,p_start,p_end):
            if i_start==i_end:return None
            #print 'create root',postorder[p_end-1]
            root=TreeNode(postorder[p_end-1])
            root_idx=inorder[i_start:i_end].index(root.val)
            #print 'create left root'
            root.left=buildTree(i_start,i_start+root_idx,p_start,p_start+root_idx)
            #print 'create right root'
            root.right=buildTree(i_start+root_idx+1,i_end,p_start+root_idx,p_end-1)
            return root
        
        if not inorder or not postorder:
            return None
        return buildTree(0,len(inorder),0,len(postorder))
      
            
            

相关文章

网友评论

      本文标题:106. Construct Binary Tree from

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