题目描述:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
和有序链表化为BST方法一样,递归求解; 注:中间必须要两个中间结点的后一个!
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
if(num == null||num.length == 0)
return null;
return helper(num,0,num.length-1);
}
public TreeNode helper(int []num,int low ,int high)
{
if(low>high)
return null;
int center=low+(high-low)/2;
//若数组元素个数为偶数,则中间结点选取两个中的后一个。
if((high-low)%2==1)
center++;
TreeNode node=new TreeNode(num[center]);
node.left=helper(num,low,center-1);
node.right=helper(num,center+1,high);
return node;
}
}