首页 > 其他 > 详细

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

时间:2020-08-30 17:04:07      阅读:66      评论:0      收藏:0      [点我收藏+]

技术分享图片
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

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

原文:https://www.cnblogs.com/panweiwei/p/13585625.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!