首页 > 其他 > 详细

leetcode-105-从前序与中序遍历构造二叉树

时间:2019-07-14 17:36:42      阅读:93      评论:0      收藏:0      [点我收藏+]

题目描述:

  技术分享图片

方法一:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        def helper(in_left=0,in_right=len(inorder)):
            nonlocal pre_idx 
            # if there is no elements to construct subtrees 
            if in_left == in_right: return None 
            # pick up pre_idx element as a root 
            root_val = preorder[pre_idx] 
            root = TreeNode(root_val) 
            # root splits inorder list 
            # into left and right subtrees 
            index = idx_map[root_val] 
            # recursion 
            pre_idx += 1 
            # build left subtree 
            root.left = helper(in_left, index) 
            # build right subtree 
            root.right = helper(index + 1, in_right) 
            return root 
        # start from first preorder element 
        pre_idx = 0 
        # build a hashmap value -> its index 
        idx_map = {val:idx for idx, val in enumerate(inorder)} 
        return helper()

 

leetcode-105-从前序与中序遍历构造二叉树

原文:https://www.cnblogs.com/oldby/p/11184886.html

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