leetcode第106题从中序与后序遍历序列构造二叉树

跟前序中序一样的 改一下代码就可以了 

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def buildTree(self, inorder, postorder):
        dict_p_i={}
        for index_p,p in enumerate(postorder):
            dict_p_i[p]=[index_p]
        for index_i,i in enumerate(inorder):
            dict_p_i[i].append(index_i)
        sign=[False for i in inorder]
        def Con_BT(root):
            index_root=dict_p_i[root.val][1]
            if index_root-1>=0 and not sign[index_root-1]:#有左子树
                left_temp=index_root-1#左子树在中序里的索引
                left_temp_last=dict_p_i[inorder[left_temp]][0]#左子树对应的数值在前序里的索引
                while left_temp>=0 and not sign[left_temp]:
                    temp_a=dict_p_i[inorder[left_temp]][0]
                    if temp_a>left_temp_last:
                        left_temp_last=temp_a
                    left_temp-=1
            if index_root+1<=len(inorder)-1 and not sign[index_root+1]:
                right_temp=index_root+1
                right_temp_last=dict_p_i[inorder[right_temp]][0]
                while right_temp<=len(inorder)-1 and not sign[right_temp]:
                    temp_b=dict_p_i[inorder[right_temp]][0]
                    if temp_b>right_temp_last:
                        right_temp_last=temp_b
                    right_temp+=1
            if index_root-1>=0 and not sign[index_root-1]:
                sign[dict_p_i[postorder[left_temp_last]][1]]=True
                root.left=TreeNode(postorder[left_temp_last])
                Con_BT(root.left)
            if index_root+1<=len(inorder)-1 and not sign[index_root+1]:
                sign[dict_p_i[postorder[right_temp_last]][1]]=True
                root.right=TreeNode(postorder[right_temp_last])
                Con_BT(root.right)
        a=TreeNode(postorder[-1])
        sign[dict_p_i[postorder[-1]][1]]=True
        Con_BT(a)
        return a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值