Leetcode: Maximum Binary Tree

Maximum Binary Tree


<a href=”https://github.com/dennyzhang/code.dennyzhang.com/tree/master/problems/example“><img align=”right” width=”200″ height=”183″ src=”github.png” /></a>

Similar Problems:


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,0,5]
Output: return the tree root node representing the following tree:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1

Note:

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

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// Basic Ideas: recursive
// Complexity: Time O(n*n), Space O(1)
// Blog link: https://code.dennyzhang.com/maximum-binary-tree
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func constructMaximumBinaryTree(nums []int) *TreeNode {
    if len(nums) == 0 { return nil }
    k := 0
    for i, _ := range nums {
        if nums[i] > nums[k] { k = i }
    }
    res := TreeNode{nums[k], nil, nil}
    res.Left = constructMaximumBinaryTree(nums[0:k])
    res.Right = constructMaximumBinaryTree(nums[k+1:])
    return &res
}

<div style=”overflow: hidden;”>

<div style=”float: left; padding: 5px”> <a href=”https://www.linkedin.com/in/dennyzhang001“><img src=”linkedin.png” alt=”linkedin” /></a></div>

<div style=”float: left; padding: 5px”><a href=”https://github.com/dennyzhang“><img src=”github.png” alt=”github” /></a></div>

<div style=”float: left; padding: 5px”><a href=”https://www.dennyzhang.com/slack” target=”_blank” rel=”nofollow”><img src=”slack.png” alt=”slack”/></a></div>

</div>


Share It, If You Like It.

Leave a Reply

Your email address will not be published.