Construct Binary Tree from Inorder and Postorder Traversal

思路和依据前序遍历和中序遍历重建树的思路一样,复杂度也一致,代码如下:

class Solution(object):
    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        if not inorder:
            return None
        length = len(inorder)
        map = {}
        for i in xrange(length):
            map[inorder[i]] = i
        return self.helper(postorder,0,length-1,0,length-1,map)
            
    def helper(self,postorder,Istart,Iend,Pstart,Pend,map):
        if Istart > Iend:
            return None
        node = TreeNode(postorder[Pend])
        if Istart == Iend:
            return node
        index = map[node.val]
        node.left = self.helper(postorder,Istart,index-1, Pstart,Pstart+index-Istart-1,map)
        node.right = self.helper(postorder,index+1,Iend,Pstart+index-Istart,Pend-1,map)
        return node

 

转载于:https://www.cnblogs.com/sherylwang/p/5405724.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值