AlgoFrames

Build a balanced BST from a sorted array

Challenge · Write code · about 20 min

The array nums holds distinct integers in increasing order. Build a height-balanced BST that holds every key and return its root.

Make the tree unique: the root of each range lo..hi is the key at index (lo + hi) / 2 rounded down. Its left subtree is built from the keys before it, its right subtree from the keys after it.

Example 1

Input:

[[-10,-3,0,5,9]]

Output:

[0,-10,5,null,-3,null,9]

0 is the middle key, so it becomes the root.

Example 2

Input:

[[1,3]]

Output:

[1,null,3]

Indices 0 to 1: the middle index is 0.

Constraints

  • 0 ≤ nums.length ≤ 1,000
  • -1,000 ≤ nums[i] ≤ 1,000
  • nums is sorted in strictly increasing order

Learn the idea first: Why balance matters, a visual lesson.

More Why balance matters problems