Maximum Binary Tree
Problem
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:
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].
Solution
Recursive Solution using two pointers: O(n^2) time and O(n) space
public class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return helper(nums, 0, nums.length - 1);
}
private TreeNode helper(int[] nums, int left, int right) {
if (left > right) return null;
int maxIndex = left;
for (int i = left + 1; i <= right; i++) {
if (nums[i] > nums[maxIndex]) maxIndex = i;
}
TreeNode head = new TreeNode(nums[maxIndex]);
head.left = helper(nums, left, maxIndex - 1);
head.right = helper(nums, maxIndex + 1, right);
return head;
}
}
Analysis
We use a helper(int[] nums, int left, int right)
to solve this problem easily
If left > right
we know there is no valid indices and return null
We find the maxIndex
from the given left
to right
Then we create a new TreeNode
with the value of maxIndex
We set it node.left
and node.right
by recursively calling the help()
method
The left
parameter will be the left to maxIndex - 1, and right will be maxIndex + 1 to right
Notice that the time complexity is O(n^2) because each recursive call costs O(n) time