关键点,对一个有序数组,要想构造一棵 平衡BST,必须从中间的结点开始;
选取中间点可以随意选,构造的平衡BST不唯一
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0) return null;
return buildBlancedBST(nums,0,nums.length-1);
}
public TreeNode buildBlancedBST(int[] nums,int l,int r){
if(l>r) return null;
int mid = (l+r)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = buildBlancedBST(nums,l,mid-1);
root.right = buildBlancedBST(nums,mid+1,r);
return root;
}
}