105. 从前序与中序遍历序列构造二叉树


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
posted @ 2020-08-30 16:30  人间烟火地三鲜  阅读(124)  评论(0编辑  收藏  举报