KatInterview

Balanced BST Level-Order Output from a Sorted Sequence

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbinary-search-treedivide-and-conquerrecursion

Last 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:

  1. If the segment is empty, the subtree is empty (no node).
  2. Otherwise, let the segment have length n. The root is the element at offset n // 2 within the segment (counting from 0). For even n this is the upper (right) of the two middle elements.
  3. 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. A None entry has no children of its own and adds nothing further.
  • After the traversal, remove all trailing None entries.
  • If values is 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^9
  • values is sorted in non-decreasing order (duplicates are possible and are placed purely by position).
  • Aim for O(N) time and O(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.