Skip to the code
cf.
+10 XP

#338 Balanced Index From Sorted IDs

easy

A client-side search index receives user ids already sorted ascending. To keep lookups fast, it builds a binary search tree that is as balanced as possible.

Write buildIndex(ids) that returns the root of a search tree built like this: the root is the middle id, at index Math.floor((low + high) / 2) of the range low..high; the ids left of it build the left subtree the same way, and the ids right of it build the right subtree. An empty array gives an empty tree.

Example 1

Input: ids = [1,2,3,4,5]
Output: [3,1,4,null,2,null,5]

The middle of indexes 0..4 is 2 (id 3). The left half [1, 2] picks index 0 (id 1), with 2 as its right child.

Example 2

Input: ids = [10,20]
Output: [10,null,20]

The middle of indexes 0..1 rounds down to 0.

Constraints

  • 0 <= ids.length <= 10000
  • ids is sorted ascending with no duplicates.

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).