sagelearnai

Convert Sorted Array to Binary Search Tree

Difficulty: Easy · Pattern: Trees & BST · LeetCode #108

Given an integer array nums sorted in ascending order, convert it into a height-balanced BST. Several balanced trees are valid. Choosing the lower or upper middle element at each step gives different trees, and the tests accept either consistent choice.

Examples

text
nums = [-10,-3,0,5,9]  →  [0,-3,9,-10,null,5]  (or [0,-10,5,null,-3,null,9])
nums = [1,3]           →  [3,1]  (or [1,null,3])

Hints

  1. Which element should be the root so that both sides have nearly equal size?
  2. The left half becomes the left subtree, the right half the right subtree. Recurse.

Approach

Pick mid = (lo + hi) // 2 as the root, then build the left subtree from [lo, mid-1] and the right subtree from [mid+1, hi]. The two halves differ in size by at most 1 at every node, so the tree is height-balanced. Inorder of the result is exactly nums, so it is a valid BST.

Pass indices instead of slicing. Slicing copies arrays and pushes the cost to O(n log n).

Complexity

Time: O(n). Space: O(log n) recursion.

Python solution
def sortedArrayToBST(nums):
    def build(lo, hi):
        if lo > hi:
            return None
        mid = (lo + hi) // 2
        node = TreeNode(nums[mid])
        node.left = build(lo, mid - 1)
        node.right = build(mid + 1, hi)
        return node
    return build(0, len(nums) - 1)
JavaScript solution
function sortedArrayToBST(nums) {
  const build = (lo, hi) => {
    if (lo > hi) return null;
    const mid = (lo + hi) >> 1;
    const node = new TreeNode(nums[mid]);
    node.left = build(lo, mid - 1);
    node.right = build(mid + 1, hi);
    return node;
  };
  return build(0, nums.length - 1);
}