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.
Thoughts
思路和构建BST类似。只是每次分界点是数组所在范围内的最大值。
Code
class Solution {
private int findMax(int[] nums, int start, int end) {
int max = nums[start], index = start;
for (int i = start + 1; i <= end; i++) {
if (nums[i] > max) {
max = nums[i];
index = i;
}
}
return index;
}
private TreeNode helper(int[] nums, int start, int end) {
if (start > end) {
return null;
}
int division = findMax(nums, start, end);
TreeNode node = new TreeNode(nums[division]);
node.left = helper(nums, start, division - 1);
node.right = helper(nums, division + 1, end);
return node;
}
public TreeNode constructMaximumBinaryTree(int[] nums) {
return helper(nums, 0, nums.length - 1);
}
}