Convert Sorted Array to Binary Search Tree (LeetCode 108): Solution and Explanation

Easy
Array
Divide And Conquer
Tree
Binary Search Tree
Binary Tree

You get an array of integers sorted in ascending order and must build a binary search tree from it whose left and right subtrees never differ in height by more than one at any node. Any valid balanced BST is accepted, so there can be several correct outputs.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A sorted array is already the in-order traversal of every BST that holds those values. So the question is not which order the values go in, but which value should sit at the root. If you pick the first element as the root, everything else lands in the right subtree and the tree degenerates into a linked list of height n, which is exactly what the balance rule forbids.

The balance rule pushes you toward the middle. If the root is the middle element, the left half of the array becomes the left subtree and the right half becomes the right subtree, and the two halves differ in size by at most one. Apply the same idea to each half and every node ends up with subtrees of nearly equal size, which keeps the heights within one of each other.

That gives a clean divide and conquer recursion over index ranges. Instead of slicing the array (which copies data), you pass left and right bounds, compute mid, create a node for nums[mid] and recurse on [left, mid - 1] and [mid + 1, right]. An empty range returns None, which is the base case.

Approach: Divide and conquer on the middle element

  1. Define a helper build(left, right) that returns the root of a balanced BST built from nums[left..right].
  2. If left > right the range is empty, so return None.
  3. Compute mid = (left + right) // 2, the middle index of the range (the left middle when the size is even).
  4. Create a TreeNode holding nums[mid].
  5. Set node.left to build(left, mid - 1) and node.right to build(mid + 1, right).
  6. Return the node, and call build(0, len(nums) - 1) to get the whole tree.

Step-by-step example

nums = [-10, -3, 0, 5, 9]
  1. build(0, 4) picks mid = 2, so the root is 0.
  2. The left call build(0, 1) picks mid = 0, creating node -10. Its left call build(0, -1) returns None, and its right call build(1, 1) creates node -3.
  3. The right call build(3, 4) picks mid = 3, creating node 5. Its left range is empty and its right call build(4, 4) creates node 9.
  4. The finished tree in level order is [0, -10, 5, null, -3, null, 9], and every node has subtree heights that differ by at most one.

Code: Python, Java, C++

1class Solution:
2    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
3        def build(left, right):
4            if left > right:
5                return None
6            mid = (left + right) // 2
7            node = TreeNode(nums[mid])
8            node.left = build(left, mid - 1)
9            node.right = build(mid + 1, right)
10            return node
11        return build(0, len(nums) - 1)

Time and space complexity

Time

O(n)

Every element becomes exactly one node and each call does constant work apart from its two recursive calls, so the total work is linear in the array length.

Space

O(log n)

Ignoring the output tree, the only extra memory is the recursion stack, and because each call halves the range the depth is about log n.

Other approaches

Right middle split (time O(n), space O(log n))

Using (left + right + 1) // 2 picks the right of the two middle elements when the range has even length. It produces a different but equally valid balanced tree, which is why several outputs are accepted.

Iterative build with an explicit stack (time O(n), space O(log n))

You can push (node, left, right) work items onto a stack instead of recursing. It avoids recursion limits in languages with shallow stacks but is longer and harder to read for no asymptotic gain.

Common mistakes

  • Slicing the array in each call, as in build(nums[:mid]), copies data at every level and pushes the time to O(n log n). Pass index bounds instead.
  • Using left >= right as the base case drops single-element ranges, so leaf nodes go missing.
  • Recursing on [left, mid] instead of [left, mid - 1] reuses the middle element and can recurse forever on a two-element range.
  • Computing mid = (left + right) / 2 in Java or C++ with huge bounds can overflow; left + (right - left) / 2 is the safe form, although array sizes here are small.

Frequently asked questions

Why pick the middle element as the root?

Choosing the middle splits the remaining values into two halves whose sizes differ by at most one. Doing that recursively keeps every subtree balanced, so the tree has height about log n instead of degrading into a chain.

Is there only one correct answer?

No. When a range has an even number of elements there are two middle candidates, and either choice gives a height-balanced BST. Judges accept any valid balanced tree.

What is the time complexity of converting a sorted array to a BST?

It is O(n) because every element is visited once to create its node. The recursion depth, and therefore the extra space, is O(log n).

How is this different from converting a sorted linked list to a BST?

With an array you can jump straight to the middle in O(1). A linked list needs either a slow and fast pointer walk to find the middle each time, which costs O(n log n), or an in-order simulation that builds the tree while advancing a list pointer in O(n).