码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-07-14 17:53:37      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:elf   hashmap   dtree   order   roo   图片   img   dex   val   

题目描述:

  技术图片

方法一:

# 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()

 另:

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        def helper(i,j):
            while i<j:
                root = TreeNode(preorder[0])
                del preorder[0]
                root.left = helper(i,idx_map[root.val])
                root.right = helper(idx_map[root.val]+1,j)
                return root
        idx_map = {val:idx for idx, val in enumerate(inorder)} 
        return helper(0,len(inorder))

 

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

标签:elf   hashmap   dtree   order   roo   图片   img   dex   val   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!