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.
  • None marks an absent left or right child. Absent children do not reserve child slots on subsequent levels, and trailing None placeholders at the end of level_order_list may 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-None entry is an integer (negative, zero, or positive).
  • Duplicate integer keys may appear in the BST.

Step-by-step walkthrough

  1. 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.val and 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, with None marking 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   9
    

    Only real (non-None) nodes receive two child slots later in the list! The None left child of 2 does not get child slots of its own. That means we cannot use heap-style index formulas (2 * i + 1 and 2 * i + 2), which would wrongly try to hang 5 and 9 under a None node. Also notice that trailing Nones at the very end (such as 5's and 9's missing children) may be omitted.

  2. Baseline shortcut vs. reconstructing the BST

    For any valid BST, filtering out None entries and calling .sort() produces the exact same sorted list in O(M log M) time for M entries — a handy one-minute sanity check in tests.

    However, sorting ignores the BST structure completely and pays an extra log M factor. 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 in O(M) linear time.

  3. Rebuild the tree with a FIFO queue of parents

    As we scan level_order_list from 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.deque in Python) keeps track of real nodes still waiting for their two children:

    1. Create root from level_order_list[0] and push root into parent_queue, starting idx = 1.
    2. Pop the oldest parent from the front of parent_queue.
    3. Read level_order_list[idx] for parent.left and idx + 1 for parent.right. Whenever a slot is not None, create a TreeNode, attach it to parent, and append it to the back of parent_queue so it will receive its own children later.
    4. Stop as soon as idx reaches the end of the list — any nodes remaining in parent_queue simply had their trailing None children omitted.
  4. Write the tree builder safely

    Two defensive checks prevent subtle bugs during deserialization:

    • Test val is not None, never if val: — 0 is a valid integer in the BST, and if val: in Python treats 0 as False and silently deletes zero-valued nodes!
    • Check idx < total_entries before reading the right child — in [8, 3], node 8 has a left child 3 at index 1, and the list ends before index 2.
    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
    
  5. 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 15
    

    Because left <= parent < right everywhere in the BST, Left -> Node -> Right automatically outputs values in sorted non-decreasing order (including duplicates).

    Why not write a three-line recursive function? Because level_order_list can have 10^5 entries! A skewed chain like [2, None, 4, None, 6, ...] has up to 50,000 levels, whereas Python's call stack raises RecursionError around depth 1,000. Replacing recursion with an explicit Python list stack eliminates that depth limit completely.

  6. Write the iterative in-order traversal

    In each iteration of the explicit-stack loop:

    • Step A (dive left): Follow .left pointers as far as possible, pushing every node onto stack so we remember to come back to it.
    • Step B (visit and step right): Once current hits None, pop the deepest waiting ancestor from stack, append current.val to sorted_values, and set current = current.right to 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
    
  7. Trace Example 1 and Example 2

    Let's trace inorder_values on Example 1 (root = 8 with children 3(1, 6) and 12(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]
    
  8. 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_tree advances idx across the M list entries once, doing O(1) deque appends and pops per real node; inorder_values pushes and pops each of the N constructed nodes on stack exactly once (O(N) <= O(M)).
  • Space: O(N) (which is O(M) in the worst case). Storing the N TreeNode objects takes O(N) memory, parent_queue holds at most one tree level (<= (N + 1) / 2 nodes), stack holds at most H ancestors along the current root-to-leaf path, and sorted_values holds N output integers. Note that in Python each TreeNode object carries much higher constant-factor memory overhead than an 8-byte list slot in sorted_values, which is why avoiding node allocations can save substantial RAM when N is large.

Edge cases

  • Empty input [] or [None]: build_tree returns None, and inorder_values(None) immediately returns [].
  • Single-node tree [5]: Loop in build_tree does not run (idx = 1 == total_entries); traversal pushes and pops 5, returning [5].
  • Zero and negative integers: Checking left_val is not None preserves 0 and negative numbers; if left_val: would mistakenly drop 0.
  • Duplicate keys: Equal values live in the left subtree (left <= parent < right), and Left -> Node -> Right emits 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 because idx < total_entries guards both the loop and the right-child read.
  • Deep skewed trees (50,000 nodes deep): [2, None, 4, None, 6, ...] has 99,999 entries and H = 50,000; the explicit stack handles 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 reserve 2 child slots, 4 grandchild 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): Raises RecursionError on skewed trees deeper than ~1,000 nodes.
  • Using list.pop(0) instead of deque.popleft(): Removing index 0 of a Python list shifts every remaining element left in O(N) time, degrading tree construction on wide trees to O(N^2).
  • Forgetting if idx < total_entries: before reading the right child: Crashes with IndexError on even-length lists like [8, 3] where the last parent specifies a left child and omits the trailing None right child.
  • Pushing None onto parent_queue: Causes None placeholders to steal child entries meant for subsequent real nodes.

Alternative approaches

  • Index arrays without TreeNode objects (O(M) time, smaller memory footprint): Run the exact same deque parent-matching pass over list indices instead of allocating TreeNode instances, recording left_idx[i] and right_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 = None link after climbing back up.
  • Filter non-None values 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 of O(N log N) comparisons instead of O(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_tree stays 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 extracted N integers explicitly in O(M + N log N) time (or O(M + K) with counting sort if values fall in a small bounded integer range K).
  • 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 + 1 and 2 * i + 2) do not work directly here because compact level-order lists omit children of None nodes (expanding a skewed N-node path into full heap layout would require 2^N - 1 slots!). However, you can still avoid TreeNode objects completely: either run the queue pass over integer array indices to populate flat left_child[i] and right_child[i] integer arrays and traverse indices in O(M) time, or simply filter out None entries and call Timsort (values.sort()) in O(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,000 list entries for 50,000 skewed nodes) because every entry and node is still processed a constant number of times. For space, parent_queue actually uses O(1) space (1 node at a time on a single path!), while the traversal's stack grows to O(H) entries — a naive recursive traversal would crash Python's default 1,000-frame call stack with RecursionError, whereas our iterative stack list safely stores 50,000 references on the heap (and Morris traversal could reduce extra traversal space further to O(1)).

Follow-up questions

Similar questions

More Moody's interview questions

All 2 Moody's questions →