InterviewPrepKit

Home / Coding / Trees

Convert Sorted Array to Binary Search Tree

easy Original ↗
Solving tips
  • Key insight: a sorted array is a BST's inorder sequence, so picking the middle element as root and recursing on each half guarantees height balance.
  • Do NOT insert values one at a time — sorted input degenerates into a linked-list-shaped tree; you must choose roots, not insert.
  • Pass (lo, hi) index bounds instead of slicing the array to keep it O(n) time and O(log n) stack space.
  • Pitfall: base case is lo > hi returns None; stopping at lo == hi drops single-element ranges. Any balanced BST is accepted, so either middle on even lengths is fine.

Problem

You are given an integer array nums sorted in strictly increasing order. Build and return a height-balanced binary search tree containing exactly these values — height-balanced meaning at every node, the left and right subtree heights differ by at most 1.

Any valid answer is accepted; many differently-shaped balanced BSTs can hold the same values.

Examples

Example 1

Input:  nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]   (one valid answer)

         0
        / \
      -3   9
      /   /
    -10  5

0 is the middle element; everything smaller goes left, everything larger goes right, recursively.

Example 2

Input:  nums = [1,3]
Output: [3,1]  — and [1,null,3] is equally valid.

With an even count there is no unique middle; either choice yields a balanced BST.

Constraints

  • 1 <= nums.length <= 10^4 — an O(n) construction is expected.
  • -10^4 <= nums[i] <= 10^4, strictly increasing — no duplicates to worry about.

Think about it first

Hint 1 An inorder traversal of a BST visits values in sorted order — so `nums` is exactly the inorder sequence of the tree you must build. Which element should be the root so the two sides come out the same size?
Hint 2 Inserting the values one by one into an ordinary BST fails spectacularly: sorted input builds a linked-list-shaped tree. You need to pick roots, not insert.
Hint 3 Take the middle element as the root, then recursively build the left subtree from the left half and the right subtree from the right half — halving guarantees the height balance.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.