Convert Sorted Array to Binary Search Tree

EasyBinary Tree · Divide & Conquer🧩 Tree DFSLeetCode #108 ↗Updated

Problem

You get an integer array nums sorted in strictly increasing order. Build a binary search tree containing exactly these values that is height-balanced (at every node the two subtree heights differ by at most 1) and return its root. Any valid balanced BST is accepted.
Input[-10,-3,0,5,9]Output[0,-3,9,-10,null,5]
Input[1,3]Output[3,1] or [1,null,3]

1 ≤ n ≤ 104  ·  -104 ≤ nums[i] ≤ 104  ·  nums is strictly increasing

Try it yourself

Java
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The sorted array is the in-order traversal of the answer. Pick the middle element as the root: the halves on each side differ in size by at most 1, so recursing on them keeps every subtree balanced.
PatternTree DFS

Instinct If the answer for a node can be built from the answers of its left and right subtrees, write one recursive function and trust it on the children.

Memory hack Ask the kids, then decide - each child reports up, the parent combines, and a global variable keeps the best "bend" seen so far.

Open the Tree DFS guide →

Approaches

Brute ForceRecursion on Copied Halves

Time O(n log n)Space O(n)

Take nums[mid] as the root, then literally cut the array into two new arrays with Arrays.copyOfRange and recurse on each. Every recursion level copies about n elements in total, and there are log n levels.

Java
public TreeNode sortedArrayToBST(int[] nums) {
    if (nums.length == 0) return null;
    int mid = nums.length / 2;
    TreeNode root = new TreeNode(nums[mid]);
    root.left = sortedArrayToBST(Arrays.copyOfRange(nums, 0, mid));
    root.right = sortedArrayToBST(Arrays.copyOfRange(nums, mid + 1, nums.length));
    return root;
}

Natural first draft, but the array copies add a log n factor and O(n) memory.

At a glance

LevelApproachTimeSpace
Brute ForceRecursion on Copied HalvesO(n log n)O(n)
BetterIterative with an Explicit StackO(n)O(log n)
OptimalDivide & Conquer on Index RangeO(n)O(log n)
Common pitfalls
  • Inserting values one by one into a plain BST — sorted input builds a skewed, unbalanced chain.
  • Off-by-one in ranges: use mid - 1 / mid + 1, and stop when lo > hi.
  • Expecting one exact output — left-middle and right-middle choices are both valid.
Interview tips
  • Start from the observation “in-order of a BST is sorted”.
  • Explain why the middle root guarantees balance (halves differ by ≤ 1).
  • Mention passing indices instead of slicing to avoid O(n log n) copying.
Pattern
Divide & conquer on a sorted range → build balanced structures by recursing on the middle.
My notes saved in this browser