跟前序中序一样的 改一下代码就可以了
# 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