【题目】Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
【思路】其实这道题目没有我开始想的那么复杂,因为题目给的num已经是sorted好的了,所以不用一个个插入判断,而是直接利用这一点,选取中间的元素作为root,然后左子树和右子树分别递归调用helper函数,用相同的方法确定下来。有点象二分法。
【代码】
public static TreeNode convert(int[] num){
if(num.length==0) return null;
TreeNode head=helper(num,0,num.length-1);
return head;
}
public static TreeNode helper(int[] num,int start,int end){
if(start>end) return null;
int mid=(start+end)/2;
TreeNode cur=new TreeNode(num[mid]);
cur.left=helper(num,start,mid-1);
cur.right=helper(num,mid+1,end);
return cur;
}