Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
/**
* 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(nums, 0, nums.length);
}
private TreeNode createTree(int[] nums, int from, int to)
{
if(from>=to)
return null;
int len = to - from;
if(len==1)
return new TreeNode(nums[from]);
int rootIndexOffset = len%2==0 ? len/2 : (len-1)/2;
int rootIndex = from + rootIndexOffset;
TreeNode root = new TreeNode(nums[rootIndex]);
root.left = createTree(nums, from, rootIndex);
root.right = createTree(nums, rootIndex+1, to);
return root;
}
}