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

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
上一篇:基于VB.NET和S7-200SMART的上位机组态控制系统设计任务书


下一篇:Spark Streaming + Spark SQL 实现配置化ETL流程