Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Difficulty: Medium
/**
* 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 helper(int[] nums, int begin, int end){
if(end < begin) return null;
if(begin == end) return (new TreeNode(nums[begin]));
if(end - begin == 1){
TreeNode root = new TreeNode(nums[begin]);
root.right = helper(nums, end, end);
return root;
}
int mid = (end - begin)/2 + begin;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums, begin, mid - 1);
root.right = helper(nums, mid + 1, end);
return root;
}
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0) return null;
return helper(nums, 0, nums.length - 1);
}
}