Question
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
*Difficulty: Medium, Frequency: Low
My Solution
O(n) runtime, O(log n) stack space – Divide and conquer
/**
* 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) {
if(nums.length == 0) return null;
return getSubtree(nums, 0, nums.length-1);
}
public TreeNode getSubtree(int[]nums, int start, int end){
int rootInd = (start + end)/2;
TreeNode node = new TreeNode(nums[rootInd]);
node.left = (start <= rootInd-1) ? getSubtree(nums, start, rootInd-1) : null;
node.right = (rootInd+1 <= end) ? getSubtree(nums, rootInd+1, end) : null;
return node;
}
}