思想:然后因为要高度平衡,可以利用折半思想来构造,每次选当前区间的mid位置来作为root来构造这样保证左右子树中节点数一致不会导致不平衡。然后为了保证BST的特性,左孩子从[start,mid-1]来构成,同理右孩子从[mid+1,end]来构造
class Solution {
public TreeNode helper(int[]nums,int start,int end){
if(start>end)return null;
int mid = (start+end)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums,start,mid-1);
root.right = helper(nums,mid+1,end);
return root;
}
public TreeNode sortedArrayToBST(int[] nums) {
int len = nums.length;
return helper(nums,0,len-1);
}
}