利用递归来一层层的建造
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return core(nums,0,nums.length-1);
}
public TreeNode core(int[] nums,int lo,int hi){
if(lo>hi)return null;
int maxIndex=-1;
int max=Integer.MIN_VALUE;
for(int i=lo;i<=hi;i++){
if(nums[i]>max){
max=nums[i];
maxIndex=i;
}
}
TreeNode root=new TreeNode(max);
root.left=core(nums,lo,maxIndex-1);
root.right=core(nums,maxIndex+1,hi);
return root;
}
}