Extract Sorted Keys from a Level-Order BST
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Given a compact breadth-first (level-by-level) array encoding of a Binary Search Tree (BST), rebuild the tree and return all stored integer keys in non-decreasing order.
Implement the following function:
def get_sorted_bst_values(level_order_list: list[int | None]) -> list[int]:
Encoding and ordering rules:
- Entries appear level by level from root downward, scanning left to right within each level.
Nonemarks an absent left or right child. Absent children do not reserve child slots on subsequent levels, and trailingNoneplaceholders at the end oflevel_order_listmay be omitted. Both[]and[None]denote an empty tree.- Every node obeys the BST invariant: keys in its left subtree are less than or equal to the node's key (
<=), and keys in its right subtree are strictly greater than the node's key (>). - Your implementation must handle arbitrarily skewed trees up to the maximum input size without hitting call-stack limits.
Examples
Example 1
Input: level_order_list = [8, 3, 12, 1, 6, 10, 15]
Output: [1, 3, 6, 8, 10, 12, 15]
Walk-through:
- Root 8 has left child 3 (with children 1 and 6) and right child 12 (with children 10 and 15).
- Visiting left subtree, node, and right subtree produces [1, 3, 6, 8, 10, 12, 15].
Example 2
Input: level_order_list = [2, None, 7, 5, 9]
Output: [2, 5, 7, 9]
Walk-through:
- Root 2 has no left child (None) and right child 7. Because the None slot has no children of its own, the next two entries (5 and 9) attach as the left and right children of 7.
- Collecting keys in ascending order yields [2, 5, 7, 9].
Constraints
0 <= len(level_order_list) <= 10^5- Each non-
Noneentry is an integer (negative, zero, or positive). - Duplicate integer keys may appear in the BST.
Step-by-step walkthrough
Understand the compact level-order format
We are given a Binary Search Tree (BST) — a binary tree where every node in a parent's left subtree has a value
<= parent.valand every node in its right subtree has a value> parent.val— serialized into a flat list level by level, top to bottom and left to right, withNonemarking missing children. Our job is to rebuild the tree and return all integer values in ascending (non-decreasing) order.Before writing any code, look closely at Example 2:
[2, None, 7, 5, 9]. Notice how slots are assigned:Index: 0 1 2 3 4 Entry: [ 2, None, 7, 5, 9 ] | \___/ | \__/ root 2's 2 | 7's 2 slots | slots Resulting tree: 2 / \ None 7 / \ 5 9Only real (non-
None) nodes receive two child slots later in the list! TheNoneleft child of2does not get child slots of its own. That means we cannot use heap-style index formulas (2 * i + 1and2 * i + 2), which would wrongly try to hang5and9under aNonenode. Also notice that trailingNones at the very end (such as5's and9's missing children) may be omitted.Baseline shortcut vs. reconstructing the BST
For any valid BST, filtering out
Noneentries and calling.sort()produces the exact same sorted list inO(M log M)time forMentries — a handy one-minute sanity check in tests.However, sorting ignores the BST structure completely and pays an extra
log Mfactor. By actually reconstructing the tree and walking it in in-order (Left -> Node -> Right), we use the BST ordering guarantee directly and solve the problem inO(M)linear time.Rebuild the tree with a FIFO queue of parents
As we scan
level_order_listfrom left to right, pairs of child entries appear in the exact order their parent nodes were created. A FIFO queue (first-in, first-out line,collections.dequein Python) keeps track of real nodes still waiting for their two children:- Create
rootfromlevel_order_list[0]and pushrootintoparent_queue, startingidx = 1. - Pop the oldest
parentfrom the front ofparent_queue. - Read
level_order_list[idx]forparent.leftandidx + 1forparent.right. Whenever a slot is notNone, create aTreeNode, attach it toparent, and append it to the back ofparent_queueso it will receive its own children later. - Stop as soon as
idxreaches the end of the list — any nodes remaining inparent_queuesimply had their trailingNonechildren omitted.
- Create
Write the tree builder safely
Two defensive checks prevent subtle bugs during deserialization:
- Test
val is not None, neverif val:—0is a valid integer in the BST, andif val:in Python treats0asFalseand silently deletes zero-valued nodes! - Check
idx < total_entriesbefore reading the right child — in[8, 3], node8has a left child3at index1, and the list ends before index2.
from typing import Optional from collections import deque class TreeNode: def __init__(self, val: int) -> None: self.val = val self.left: Optional["TreeNode"] = None self.right: Optional["TreeNode"] = None def build_tree(level_order_list: list[int | None]) -> Optional[TreeNode]: # Empty list [] or [None] represents an empty tree if not level_order_list or level_order_list[0] is None: return None root = TreeNode(level_order_list[0]) # parent_queue: FIFO queue of real TreeNode objects waiting for their left/right children # Example mini-shape: deque([TreeNode(8), TreeNode(3), TreeNode(12)]) parent_queue = deque([root]) idx = 1 total_entries = len(level_order_list) # Phase 1: Reconstruct the BST level by level. Only non-None nodes enter parent_queue, # because missing (None) nodes do not consume child slots later in the list. while parent_queue and idx < total_entries: parent = parent_queue.popleft() # Assign left child from current slot; check `is not None` so value 0 is kept! left_val = level_order_list[idx] if left_val is not None: parent.left = TreeNode(left_val) parent_queue.append(parent.left) idx += 1 # Guard `idx < total_entries` because trailing None slots may be omitted (e.g., [8, 3]) if idx < total_entries: right_val = level_order_list[idx] if right_val is not None: parent.right = TreeNode(right_val) parent_queue.append(parent.right) idx += 1 return root- Test
Why we use an iterative stack for in-order traversal
An in-order traversal visits every node's entire left subtree first, then the node itself, then its entire right subtree:
8 / \ In-order visits: 3 12 left of 8 -> [1, 3, 6], then 8, then right of 8 -> [10, 12, 15] / \ / \ Result: [1, 3, 6, 8, 10, 12, 15] 1 6 10 15Because
left <= parent < righteverywhere in the BST,Left -> Node -> Rightautomatically outputs values in sorted non-decreasing order (including duplicates).Why not write a three-line recursive function? Because
level_order_listcan have10^5entries! A skewed chain like[2, None, 4, None, 6, ...]has up to50,000levels, whereas Python's call stack raisesRecursionErroraround depth1,000. Replacing recursion with an explicit Python liststackeliminates that depth limit completely.Write the iterative in-order traversal
In each iteration of the explicit-stack loop:
- Step A (dive left): Follow
.leftpointers as far as possible, pushing every node ontostackso we remember to come back to it. - Step B (visit and step right): Once
currenthitsNone, pop the deepest waiting ancestor fromstack, appendcurrent.valtosorted_values, and setcurrent = current.rightto repeat the same process on its right subtree.
from typing import List, Optional def inorder_values(root: Optional[TreeNode]) -> list[int]: # sorted_values: output values collected in Left -> Node -> Right order sorted_values: List[int] = [] # stack: explicit LIFO stack of ancestor TreeNodes whose left subtrees are being explored. # Using an explicit stack avoids Python's ~1000-call recursion limit on skewed trees. stack: List[TreeNode] = [] current = root # Phase 2: Iterative in-order traversal (Left -> Node -> Right) while stack or current is not None: # Step A: Walk all the way down the left spine, saving ancestors to revisit later while current is not None: stack.append(current) current = current.left # Step B: Left subtree is done; visit the node on top of the stack, then step right current = stack.pop() sorted_values.append(current.val) current = current.right return sorted_values- Step A (dive left): Follow
Trace Example 1 and Example 2
Let's trace
inorder_valueson Example 1 (root = 8with children3(1, 6)and12(10, 15)) and Example 2 ([2, None, 7, 5, 9]):Example 1 (balanced BST): Dive left from 8: push 8, push 3, push 1 -> current = None, stack = [8, 3, 1] Pop 1 -> sorted = [1], step to 1.right (None) Pop 3 -> sorted = [1, 3], step to 3.right (6) -> push 6 -> pop 6 -> sorted = [1, 3, 6] Pop 8 -> sorted = [1, 3, 6, 8], step to 8.right (12) Dive left from 12: push 12, push 10 -> pop 10 -> pop 12 -> push/pop 15 Final sorted_values = [1, 3, 6, 8, 10, 12, 15] Example 2 ([2, None, 7, 5, 9]): Build: pop 2 (left=None, right=7), pop 7 (left=5, right=9), idx=5 -> done In-order: push 2 (left is None) -> pop 2, sorted=[2], move to 2.right (7) dive left from 7: push 7, push 5 -> pop 5, sorted=[2, 5], move to 5.right (None) pop 7, sorted=[2, 5, 7], move to 7.right (9) -> push/pop 9 -> sorted=[2, 5, 7, 9]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque class TreeNode: def __init__(self, val: int) -> None: self.val = val self.left: Optional["TreeNode"] = None self.right: Optional["TreeNode"] = None def build_tree(level_order_list: list[int | None]) -> Optional[TreeNode]: # Empty list [] or [None] represents an empty tree if not level_order_list or level_order_list[0] is None: return None root = TreeNode(level_order_list[0]) # parent_queue: FIFO queue of real TreeNode objects waiting for their left/right children # Example mini-shape: deque([TreeNode(8), TreeNode(3), TreeNode(12)]) parent_queue = deque([root]) idx = 1 total_entries = len(level_order_list) # Phase 1: Reconstruct the BST level by level. Only non-None nodes enter parent_queue, # because missing (None) nodes do not consume child slots later in the list. while parent_queue and idx < total_entries: parent = parent_queue.popleft() # Assign left child from current slot; check `is not None` so value 0 is kept! left_val = level_order_list[idx] if left_val is not None: parent.left = TreeNode(left_val) parent_queue.append(parent.left) idx += 1 # Guard `idx < total_entries` because trailing None slots may be omitted (e.g., [8, 3]) if idx < total_entries: right_val = level_order_list[idx] if right_val is not None: parent.right = TreeNode(right_val) parent_queue.append(parent.right) idx += 1 return root def inorder_values(root: Optional[TreeNode]) -> list[int]: # sorted_values: output values collected in Left -> Node -> Right order sorted_values: List[int] = [] # stack: explicit LIFO stack of ancestor TreeNodes whose left subtrees are being explored. # Using an explicit stack avoids Python's ~1000-call recursion limit on skewed trees. stack: List[TreeNode] = [] current = root # Phase 2: Iterative in-order traversal (Left -> Node -> Right) while stack or current is not None: # Step A: Walk all the way down the left spine, saving ancestors to revisit later while current is not None: stack.append(current) current = current.left # Step B: Left subtree is done; visit the node on top of the stack, then step right current = stack.pop() sorted_values.append(current.val) current = current.right return sorted_values def get_sorted_bst_values(level_order_list: list[int | None]) -> list[int]: root = build_tree(level_order_list) return inorder_values(root)✅ Submit now — all tests should pass.
Intuition & how it works
Think of reconstructing a family tree from a roll-call sheet written generation by generation: the founder is listed first, followed by the founder's two child slots (left and right), followed by the next real person's two child slots, and so on — while blank "no child" (None) entries never have children of their own. We pair up parents with their two child slots using a FIFO queue (a first-in, first-out line, collections.deque in Python, where the earliest-created node steps up first to claim the next two entries). Once the Binary Search Tree (BST) — a binary tree where every node in the left subtree is <= its parent and every node in the right subtree is > its parent — is rebuilt, we collect sorted values with an in-order traversal (walking Left subtree -> Node -> Right subtree) driven by an explicit LIFO stack (a last-in, first-out list of ancestor nodes waiting for their left subtrees to finish).
Why do the obvious shortcuts fall short or crash? First, indexing the input like a binary heap (2 * i + 1 and 2 * i + 2) breaks as soon as any node is None, because compact level-order serialization (listing tree nodes top-to-bottom, left-to-right) omits child slots for missing nodes — on [2, None, 7, 5, 9], heap formulas look for 7's children at indices 5 and 6 instead of 3 and 4. Second, writing a recursive inorder(node) hits Python's ~1,000-frame call-stack limit (RecursionError) when 10^5 entries form a 50,000-node chain. Finally, simply sorting the non-None numbers works as an O(M log M) check, but discards the BST ordering that lets us finish in O(M) linear time.
Let's trace Example 2 ([2, None, 7, 5, 9]):
1. Build with parent_queue:
- root = 2, parent_queue = [2], idx = 1
- pop 2: slot 1 is None (2.left = None), slot 2 is 7 (2.right = 7), queue = [7], idx = 3
- pop 7: slot 3 is 5 (7.left = 5), slot 4 is 9 (7.right = 9), queue = [5, 9], idx = 5 (end!)
Tree built: 2 with no left child and right child 7 (whose children are 5 and 9).
2. Iterative in-order (Left -> Node -> Right):
- Push 2 -> 2.left is None -> pop 2 (emit 2), move to 2.right = 7
- Dive left from 7: push 7, push 5 -> 5.left is None -> pop 5 (emit 5)
- Pop 7 (emit 7), move to 7.right = 9 -> push 9 -> pop 9 (emit 9)
Output: [2, 5, 7, 9]
Complexity
Let M be len(level_order_list), N be the number of non-None nodes (N <= M), and H be the height of the reconstructed tree (log2(N) <= H <= N).
- Time:
O(M).build_treeadvancesidxacross theMlist entries once, doingO(1)dequeappends and pops per real node;inorder_valuespushes and pops each of theNconstructed nodes onstackexactly once (O(N) <= O(M)). - Space:
O(N)(which isO(M)in the worst case). Storing theNTreeNodeobjects takesO(N)memory,parent_queueholds at most one tree level (<= (N + 1) / 2nodes),stackholds at mostHancestors along the current root-to-leaf path, andsorted_valuesholdsNoutput integers. Note that in Python eachTreeNodeobject carries much higher constant-factor memory overhead than an 8-byte list slot insorted_values, which is why avoiding node allocations can save substantial RAM whenNis large.
Edge cases
- Empty input
[]or[None]:build_treereturnsNone, andinorder_values(None)immediately returns[]. - Single-node tree
[5]: Loop inbuild_treedoes not run (idx = 1 == total_entries); traversal pushes and pops5, returning[5]. - Zero and negative integers: Checking
left_val is not Nonepreserves0and negative numbers;if left_val:would mistakenly drop0. - Duplicate keys: Equal values live in the left subtree (
left <= parent < right), andLeft -> Node -> Rightemits equal keys adjacently in non-decreasing order. - Trailing
Nones present or omitted: Both[8, 3, 12, None, None, None, None]and[8, 3]work cleanly becauseidx < total_entriesguards both the loop and the right-child read. - Deep skewed trees (
50,000nodes deep):[2, None, 4, None, 6, ...]has99,999entries andH = 50,000; the explicitstackhandles it in milliseconds without touching Python's recursion limit.
Common mistakes
- Using heap index math (
2 * i + 1,2 * i + 2): Works only on full array heaps where missing nodes still reserve2child slots,4grandchild slots, and so on; on compact level-order inputs like[2, None, 7, 5, 9]or[5, 2, 8, None, 3, None, 9, None, 4], heap math orphans nodes or attaches them to the wrong parents. - Writing recursive
inorder(node): RaisesRecursionErroron skewed trees deeper than~1,000nodes. - Using
list.pop(0)instead ofdeque.popleft(): Removing index0of a Pythonlistshifts every remaining element left inO(N)time, degrading tree construction on wide trees toO(N^2). - Forgetting
if idx < total_entries:before reading the right child: Crashes withIndexErroron even-length lists like[8, 3]where the last parent specifies a left child and omits the trailingNoneright child. - Pushing
Noneontoparent_queue: CausesNoneplaceholders to steal child entries meant for subsequent real nodes.
Alternative approaches
- Index arrays without
TreeNodeobjects (O(M)time, smaller memory footprint): Run the exact samedequeparent-matching pass over list indices instead of allocatingTreeNodeinstances, recordingleft_idx[i]andright_idx[i](default-1), then run the iterative stack traversal over integer indices. - Morris in-order traversal (
O(M)time,O(1)auxiliary traversal space): Morris traversal is a pointer-threading technique that walks a binary tree in-order without a stack or recursion by temporarily pointing the rightmost node of each left subtree back up to its ancestor and restoring that.right = Nonelink after climbing back up. - Filter non-
Nonevalues and sort (O(M + N log N)time):[v for v in level_order_list if v is not None]followed by.sort()avoids building any tree at all, at the cost ofO(N log N)comparisons instead ofO(M)linear traversal.
Follow-up questions
- What changes if the serialized input represents an arbitrary binary tree with no search-tree ordering guarantee? Deserializing the tree with
build_treestays identical because level-order encoding does not depend on node ordering, or you can skip tree construction altogether and extract[v for v in level_order_list if v is not None]. Because a general binary tree makes no ordering promise between left and right subtrees, an in-order walk is no longer sorted, so you must sort the extractedNintegers explicitly inO(M + N log N)time (orO(M + K)with counting sort if values fall in a small bounded integer rangeK). - Is it possible to produce the sorted result without allocating node objects, and why do standard binary-heap index formulas fail here? Standard heap index formulas (
2 * i + 1and2 * i + 2) do not work directly here because compact level-order lists omit children ofNonenodes (expanding a skewedN-node path into full heap layout would require2^N - 1slots!). However, you can still avoidTreeNodeobjects completely: either run the queue pass over integer array indices to populate flatleft_child[i]andright_child[i]integer arrays and traverse indices inO(M)time, or simply filter outNoneentries and call Timsort (values.sort()) inO(M + N log N)time with minimal extra memory. - How do runtime and memory behave when the input encodes a degenerate chain tens of thousands of levels tall? Time complexity remains
O(M)(for example,~100,000list entries for50,000skewed nodes) because every entry and node is still processed a constant number of times. For space,parent_queueactually usesO(1)space (1node at a time on a single path!), while the traversal's stack grows toO(H)entries — a naive recursive traversal would crash Python's default1,000-frame call stack withRecursionError, whereas our iterativestacklist safely stores50,000references on the heap (and Morris traversal could reduce extra traversal space further toO(1)).
Follow-up questions
- What changes if the serialized input represents an arbitrary binary tree with no search-tree ordering guarantee?
- Is it possible to produce the sorted result without allocating node objects, and why do standard binary-heap index formulas fail here?
- How do runtime and memory behave when the input encodes a degenerate chain tens of thousands of levels tall?
Similar questions
- E-Commerce Catalog, Dynamic Pricing, and Stock Reservation System
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One