InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Convert Sorted Array to Binary Search Tree

easy Original ↗ 00:00

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, so there are no duplicates.

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: 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug