TRT
Sign in
easyAdvancedLeetCode#middle as root#divide and conquer

Convert sorted array to binary search tree

Build a height-balanced binary search tree from sorted values by making the middle value the root, recursively.

The Runtime Theory Team1 min read
Taught inWhy binary search trees degradePro — members onlyA binary search tree is only as fast as it is shallow, and its shape depends entirely on insertion order. Sorted input turns it into a linked list. Balanced trees fix the shape as they go.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [-10, -3, 0, 5, 9]

outa height-balanced BST such as [0, -3, 9, -10, null, 5]

innums = [1, 3]

out[3, 1] or [1, null, 3]

innums = [1, 2, 3, 4, 5, 6, 7]

out[4, 2, 6, 1, 3, 5, 7]

Given an array of distinct integers sorted in increasing order, build a height-balanced binary search tree containing them: one where the depths of every node's two subtrees differ by at most one.

Before you code

Inserting the values in order would build a chain. Which value should be the root so that each side receives half of the rest?

Hints

  1. Recurse on index ranges, lo and hi, rather than slicing, to keep it O(n).
  2. Make nums[mid] the root, then build the left subtree from lo to mid − 1 and the right from mid + 1 to hi.
  3. Return None for an empty range. Any choice of middle for even lengths is accepted.

Production & complexity notes

When solving Convert sorted array to binary search tree on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Why binary search trees degrade to reinforce the underlying pattern.

What it practices

Building a minimum-height tree from sorted keys, from Why binary search trees degrade.

Not started

Sign in to save your learning progress.

Sign in to save