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.
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.
Input: ids = [10,20] Output: [10,null,20]
The middle of indexes 0..1 rounds down to 0.
0 <= ids.length <= 10000ids 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.
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).
I'm here to help with #338 Balanced Index From Sorted IDs. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.