Skip to interview prep
Apexed

27. Sorted Array to a Height-Balanced BST

EasyTrees

Convert a strictly increasing array into a height-balanced binary search tree and return its root.

To make the answer unique, build it recursively: for the range lo..hi (inclusive), the root is the element at index floor((lo + hi) / 2), its left subtree is built from lo..mid − 1 and its right subtree from mid + 1..hi.

A binary tree is passed as TreeNode objects with val, left and right. The tests write trees in level order, with null for a missing child.

Example 1

Input: nums = [-10, -3, 0, 5, 9]
Output: [0, -10, 5, null, -3, null, 9]

Constraints

  • 0 ≤ nums.length ≤ 10⁴
  • nums is strictly increasing

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 5 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Sorted Array to a Height-Balanced BST — coding interview practice — Apexed