CodingNodes / Trees / Convert Sorted Array to Binary Search Tree System design Space play · ←→ step · R restart

Problem

You are given an array nums of distinct integers sorted in increasing order. Build a binary search tree from it that is height-balanced: the two subtrees of every node differ in height by at most 1.

To make the answer unique, always take the left middle element, index (lo + hi) // 2, as the root of each range. Return the root of the tree. Trees are written in level order, with null for a missing child.

Constraints

  • 1 ≤ nums.length ≤ 10000
  • -10000 ≤ nums[i] ≤ 10000
  • nums is strictly increasing

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(log n)

Time: Every array element becomes exactly one node, and each call does a constant amount of work besides its two recursive calls.

Space: Each call halves its range, so the recursion is about log n deep. The tree itself is the answer and is not counted.

In a sorted array, the middle element has about as many values on its left as on its right. Make it the root, build the left subtree from the values before it and the right subtree from the values after it. Halving every range keeps the tree balanced. An empty range gives a null child.