108. Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
这到题把有序数组转成平衡二叉搜索树,所以选取数组的中点num[mid]作为根,对左右两边分别递归。
public TreeNode sortedArrayToBST(int[] nums) {
int low=0;
int high=nums.length-1;
TreeNode root=sortedArrayToBST(nums, low, high);
return root;
}
public TreeNode sortedArrayToBST(int[] nums,int low,int high){
TreeNode root=null;
if(low<=high){
int mid=(low+high)/2;
root=new TreeNode(nums[mid]);
root.left=sortedArrayToBST(nums, low, mid-1);
root.right=sortedArrayToBST(nums, mid+1, high);
}
return root;
}