13最大二叉树
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return constructTree(nums, 0, nums.length);
}
TreeNode constructTree(int[] nums, int leftIndex, int rightIndex) {
if(rightIndex - leftIndex < 1) {
return null;
}
if(rightIndex - leftIndex == 1) {
return new TreeNode(nums[leftIndex]);
}
int maxValue = 0;
int maxIndex = 0;
for(int i = leftIndex; i < rightIndex; i++){
if(nums[i] >= maxValue) {
maxValue = nums[i];
maxIndex = i;
}
}
TreeNode root = new TreeNode(nums[maxIndex]);
root.left = constructTree(nums, leftIndex, maxIndex);
root.right = constructTree(nums, maxIndex + 1, rightIndex);
return root;
}
}