題目
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.
答案
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return recur(nums, 0, nums.length - 1);
}
public TreeNode recur(int[] nums, int left, int right) {
if(left > right) return null;
int maxi = left, max = nums[left];
for(int i = left + 1; i <= right; i++) {
if(nums[i] > max) {
max = nums[i];
maxi = i;
}
}
TreeNode maxNode = new TreeNode(max);
maxNode.left = recur(nums, left, maxi - 1);
maxNode.right = recur(nums, maxi + 1, right);
return maxNode;
}
}