题目
将有序数组转换成为转换为平衡二叉排序树,利用二分法的基本情况
例如下面这种基本情况
解题
主要是利用二分法,划分元素基本情况 ,在这里二分法要特别注意一个情况就是,如何判断
low和high 的问题即可, 单独一个元素也是可以作为一个节点的, 所有low = high 才是最终的循环判断终止条件情况
不用考虑大小问题,主要是有序数组, 平衡二叉搜索树中序遍历其实就是一个中序数组,
还是
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums==null|| nums.length==0)
return null;
return partitation(nums, 0,nums.length-1);
}
private TreeNode partitation(int []nums, int low ,int high){
if(low>high)
return null;
// 如果low ==high 的话,那么基本只有只有一个元素作为根节点的基本情况
int mid = (low+high)/2;
TreeNode root =new TreeNode(nums[mid]);
root.left = partitation(nums,low,mid-1);
root.right = partitation(nums,mid+1,high);
return root;
}
}