Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
每次递归取数组的中间值作为根节点,则左子树的根为(left,mid-1)/2对应的值,右子树根为(mid+1,right)/2
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return createTree(0,nums.length-1,nums);
}
TreeNode createTree(int left,int right,int[] nums){
if(left==right){
return new TreeNode(nums[left]);
}
else if(left>right){
return null;
}
else{
int mid=(left+right)/2;
TreeNode root=new TreeNode(nums[mid]);
root.left=createTree(left,mid-1,nums);
root.right=createTree(mid+1, right, nums);
return root;
}
}
}