Balanced BST Level-Order Output from a Sorted Sequence
Trees & GraphsAuto-graded · 22 test casesLast updated
Build a height-balanced BST from a sorted list using a fixed middle-element rule, then serialize it level by level with null placeholders.
Balanced Tree from Sorted Values
You are given values, the contents of a sorted doubly linked list in order from head to tail. Imagine turning that list into a height-balanced binary search tree, where each node's prev link becomes its left child and its next link becomes its right child. Your function works on the plain list of values and returns the shape of the resulting tree.
How the tree is built
Build the tree recursively from a contiguous segment of values:
- If the segment is empty, the subtree is empty (no node).
- Otherwise, let the segment have length
n. The root is the element at offsetn // 2within the segment (counting from 0). For evennthis is the upper (right) of the two middle elements. - The elements before the root form the left subtree. The elements after the root form the right subtree. Both are built with the same rule.
This rule always gives a height-balanced tree, and it fixes a single answer, so your output must match it exactly.
Output format
Return the tree as a level-order (breadth-first) list:
- Visit nodes level by level, left to right.
- For every real node, append its value, then consider its left child and its right child in that order.
- A missing child is written as
None. ANoneentry has no children of its own and adds nothing further. - After the traversal, remove all trailing
Noneentries. - If
valuesis empty, return[].
For instance, a root whose only child is a left child gives [root, left]. A node with only a right child gives [node, None, right].
Constraints
0 <= len(values) <= 10^5-10^9 <= values[i] <= 10^9valuesis sorted in non-decreasing order (duplicates are possible and are placed purely by position).- Aim for
O(N)time andO(log N)recursion depth, not counting the output list.
Examples
Example 1
Input: balanced_bst_level_order([1, 2, 3, 4, 5, 6, 7])
Output: [4, 2, 6, 1, 3, 5, 7]
Example 2
Input: balanced_bst_level_order([-10, -3, 0, 5, 9])
Output: [0, -3, 9, -10, None, 5]
Hints
Hint 1
A sorted sequence is exactly the in-order traversal of the tree you want, so the root of any segment is determined by its position.
Hint 2
Work with index ranges instead of slicing lists, so each element is handled once and no extra copies are made. The root of a half-open range [lo, hi) sits at (lo + hi) // 2.
Hint 3
Produce the output with a queue-based breadth-first traversal that enqueues None for missing children, then strip trailing None values at the end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A sorted list is the in-order traversal of the target tree, so the tree shape follows from positions alone.
- Build recursively over index ranges. For a half-open range
[lo, hi), return nothing if it is empty. Otherwise pickmid = (lo + hi) // 2. This equalslo + n // 2for a segment of lengthn, which is the upper median whennis even. The left subtree comes from[lo, mid)and the right subtree from[mid + 1, hi). - Serialize with BFS. Put the root in a queue. When a real node is popped, record its value and enqueue both children, using
Nonefor absent ones. When aNoneis popped, recordNoneand enqueue nothing. - Trim. Drop trailing
Nonevalues. An empty input gives[].
Why it is correct
- Search order: everything left of the root in the sorted sequence is no larger than it, and everything right of it is no smaller, so the in-order property holds at every node.
- Balance: the two sides have sizes
n // 2andn - n // 2 - 1, which differ by at most 1. By induction, the subtree heights differ by at most 1 at every node. - Exact output: the root choice is deterministic, so the tree, and therefore the level-order list, is unique.
Complexity
- Time:
O(N). Each element becomes exactly one node, and the BFS visits each node and eachNoneslot once (at most2N + 1queue entries). - Space:
O(log N)recursion depth. The temporary tuple tree and queue useO(N)memory, which is output-sized work. An in-place pointer version on real list nodes would avoid this.
Reference solution
from collections import deque
from typing import List, Optional
def balanced_bst_level_order(values: List[int]) -> List[Optional[int]]:
def build(lo, hi):
if lo >= hi:
return None
mid = (lo + hi) // 2
return (values[mid], build(lo, mid), build(mid + 1, hi))
root = build(0, len(values))
if root is None:
return []
result = []
queue = deque([root])
while queue:
node = queue.popleft()
if node is None:
result.append(None)
else:
value, left, right = node
result.append(value)
queue.append(left)
queue.append(right)
while result and result[-1] is None:
result.pop()
return result