Convert Sorted Array to Binary Search Tree

EasyTree recursionLeetCode 108 ↗World 3-12
0:00 / 0:00

Turn a sorted array into a height-balanced BST. The middle value becomes the root, and each half recursively builds its own subtree.

▼

The problem

LeetCode 108 (Easy). Given an integer array sorted in ascending order, convert it to a height-balanced binary search tree (at every node the two subtrees' heights differ by at most one).

Example (LeetCode's first, the one animated): [-10,-3,0,5,9] → [0,-3,9,-10,null,5], and [0,-10,5,null,-3,null,9] is accepted too.

TRY IT ON LEETCODE ▶

The solution

def sorted_array_to_bst(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)

Transcript

Convert Sorted Array to Binary Search Tree. You get an array, sorted from small to large. Build a binary search tree from it: smaller values to the left of each node, larger to the right. And keep it height balanced: at every node, the two sides differ in height by at most one.

Take minus ten, minus three, zero, five, nine. Zero can be the root, with minus three and nine below it, then minus ten and five. Other balanced shapes count too.

The naive way: insert the values one by one. The input is sorted, so every new value turns right, and the tree becomes a chain, five tall. That's n squared work, and it isn't balanced at all.

The key idea: divide and conquer. The middle element becomes the root. Everything left of it is smaller, so the left half builds the left subtree, and the right half builds the right. The halves differ in size by at most one, so the tree stays balanced all the way down. It's Binary Search's middle pick, used to build instead of to find.

In code, a helper builds a range, low to high. If low passes high, the range is empty: return nothing. Otherwise, mid is low plus high, halved and rounded down. Make a node from it, build the left half, then the right half, and return the node.

Let's run it on minus ten through nine. The range is zero to four, so mid is two: zero is the root. The left half, zero to one, rounds down to index zero: minus ten. Its left is empty, and minus three lands on its right. The right half picks five, with nine on its right. Rounding up instead builds LeetCode's tree; both are accepted.

Each element becomes one node, with constant work per call, so the time is O of n. The recursion is only as deep as the tree, about log n levels, so the extra space is O of log n.

Pick the middle, build both halves, and the tree balances itself. That's Convert Sorted Array to Binary Search Tree.