clueless coding // TODO: be smarter

LeetCode 108. Convert Sorted Array to Binary Search Tree: Java Solution



Problem Statement


Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Function Signature (Java):
  TreeNode sortedArrayToBST(int[] nums)

Inputs:
  nums = [-10,-3,0,5,9]

Outputs:
     0
    / \
  -3   9
  /   /
-10  5

Note that this is only one valid solution - there are other configurations that could work.



TL;DR Code Solution



public TreeNode helper(int[] nums, int left, int right) {
    if (left > right) {
        return null;
    }

    int mid = (left + right) / 2;
    TreeNode root = new TreeNode(nums[mid]);
    root.left = helper(nums, left, mid - 1);
    root.right = helper(nums, mid + 1, right);
    return root;
}

public TreeNode sortedArrayToBST(int[] nums) {
    if (nums.length == 0)
        return null;
    return helper(nums, 0, nums.length - 1);
}