Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路:建立一个平衡的二叉搜索树,我们可以以中位数为根,比它小的的是它的左子树,比它大的是它的右子树,将左右子树已同样的方法进行下去,直到左右均没有节点为止
代码如下(已通过leetcode)
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length==0) return null;
TreeNode root=createAVLBST(0,nums.length-1,nums);
return root;
}
private TreeNode createAVLBST(int low, int high, int[] nums) {
// TODO Auto-generated method stub
if(low==high) return new TreeNode(nums[low]);
else {
if(low>high) return null;
else{
int mid=(low+high)/2;
TreeNode temp=new TreeNode(nums[mid]);
temp.left=createAVLBST(low, mid-1, nums);
temp.right=createAVLBST(mid+1, high, nums);
return temp;
}
}
}
}