654 Maximum Binary Tree
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 maximum number. 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:
Note: The size of the given array will be in the range [1,1000].
The Idea: The problem initially seemed intimidating, but narrowing it down to sub problems simplifies it greatly. Using iterators for the array is a natural way to doing things, since it cleanly defines the bounds of our start and end position of nums
. Assuming the array is not empty, we begin with the maximum element in the array as the root. The left and right children of the root will then have the maximum element to the left and right of the maximum element respectively. If start == end
, then we know the array is empty and therefore contains no maximum element, so return nullptr.
Complexity: O(n^2) time and O(n) space
Last updated