因为用了很多index()运行超时了,然后因为前序和中序遍历里边没有重复元素,所以建一个hash把结点的索引放进去代替index()就行了。
# 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, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
preorder放在0,inorder放在1
"""
dict_p_i={}
for index_p,p in enumerate(preorder):
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[preorder[left_temp_last]][1]]=True
root.left=TreeNode(preorder[left_temp_last])
Con_BT(root.left)
if index_root+1<=len(inorder)-1 and not sign[index_root+1]:
sign[dict_p_i[preorder[right_temp_last]][1]]=True
root.right=TreeNode(preorder[right_temp_last])
Con_BT(root.right)
a=TreeNode(preorder[0])
sign[dict_p_i[preorder[0]][1]]=True
Con_BT(a)
return a