加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[LeetCode] 654. Maximum Binary Tree_Medium tag: stack

发布时间:2020-12-14 04:47:12 所属栏目:大数据 来源:网络整理
导读:Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the max

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

?

Construct the maximum tree by the given array and output the root node of this tree.

Example 1:

Input: [3,2,1,6,5]
Output: return the tree root node representing the following tree:

      6
    /      3     5
        / 
     2  0   
               1

?

Note:

  1. The size of the given array will be in the range [1,1000].

1. divide and conquer,最坏的时间复杂度为O(n^2),average 时间复杂度为 O(n * lg n).

Code

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

class Solution:
    def constructMaximumBinaryTree(self,nums: List[int]) -> TreeNode:
        if not nums: return 
        def helper(nums,start,end):
            if start > end: return
            if start == end: 
            for index,num in enumerate(nums[start : end + 1],start):  #start from start
                if index == start or num > nums[maxIndex]:
                    maxIndex = index
            root = TreeNode(nums[maxIndex])
            root.left = helper(nums,maxIndex - 1)
            root.right = helper(nums,maxIndex + 1,end)
            return root
        return helper(nums,len(nums) - 1)

?

2. 实际上这个题目类似于[LeetCode] 84. Largest Rectangle in Histogram_Hard tag: stack, 我们实际上求的是每个num的向左第一个比num大的数,和向右第一个比num大的数,取其中较小的,作为parent node,所以我们要用到strict decreasing stack,这里我们将maxNum加到nums的后面,这样能保证最后的结果。

Code:? ?T: O(n)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self,nums: List[int]) -> TreeNode:
        if not nums: return
        stack,maxNum = [],max(nums)
        for num in (nums + [maxNum]):
       cur = TreeNode(num)
while stack and stack[-1].val <= num: # in stack,is TreeNode node = stack.pop() if stack and stack[-1].val <= num: stack[-1].right = node else: cur.left = node stack.append(cur) return stack[0].left

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读