Description
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:
Note:
- The size of the given array will be in the range [1,1000].
Solution
Recursive, time O(nlogn) worst O(n^2)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructTree(nums, 0, nums.length - 1);
}
public TreeNode constructTree(int[] nums, int i, int j) {
if (i > j) {
return null;
}
int k = searchMaxIndex(nums, i, j);
TreeNode root = new TreeNode(nums[k]);
root.left = constructTree(nums, i, k - 1);
root.right = constructTree(nums, k + 1, j);
return root;
}
public int searchMaxIndex(int[] nums, int i, int j) {
int maxIndex = i;
for (int k = i + 1; k <= j; ++k) {
if (nums[maxIndex] < nums[k]) {
maxIndex = k;
}
}
return maxIndex;
}
}