题目
大致思路
- 将有序数组转换为二叉平衡树,即左边的数和右边数的差值不超过1,那么root节点应该为正中间的数,然后左边的剩余的中间为root.left,右边的数的正中间的为root.right,依次进行递归即可。
代码实现
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums == null || nums.length == 0)
return null;
else
return getTree(nums,0,nums.length-1);
}
public static TreeNode getTree(int[] nums,int left,int right){
while(left<=right){
int mid = (left+right)/2;
TreeNode tn = new TreeNode(nums[mid]);
tn.left = getTree(nums,left,mid-1);
tn.right = getTree(nums,mid+1,right);
return tn;
}
return null;
}
}