class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
self.preindex = 0
# 用字典存储中序序列中root的值与下标
indict = {v: i for i, v in enumerate(inorder)}
root = self.dg(0, len(preorder) - 1, preorder, inorder, indict)
return root
def dg(self, start, end, preorder, inorder, indict):
if start <= end:
# 利用字典:index = dict[val]
rindex = indict[preorder[self.preindex]]
self.preindex += 1
root = TreeNode(inorder[rindex])
root.left = self.dg(start, rindex - 1, preorder, inorder, indict)
root.right = self.dg(rindex + 1, end, preorder, inorder, indict)
return root