Depth-Grouped Binary Tree Traversal

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Given a binary tree encoded as a compact breadth-first list root, group its node values by depth from top to bottom and return them as a nested list List[List[int]].

def level_order(root: List[Optional[int]]) -> List[List[int]]:

Input encoding and output rules:

  • Both [] and [None] represent an empty tree and must return [].
  • Otherwise, root[0] holds the value of the root node (depth 0). Each non-None node, visited from top to bottom and left to right, consumes the next two entries in root for its (left_child, right_child) (None indicates a missing child; missing children consume no child slots of their own, and trailing None entries may be omitted).
  • Output index d (0-indexed) contains all values at depth d, ordered strictly from left to right.

Examples

Example 1

Input: root = [8, 4, 12, None, None, 10, 14]
Output: [[8], [4, 12], [10, 14]]

Node 8 sits at depth 0 with children 4 and 12 at depth 1. Node 4 has no children (None, None), while node 12 has children 10 and 14 at depth 2.

Example 2

Input: root = [10, 5, 18, None, 7, 15, None]
Output: [[10], [5, 18], [7, 15]]

At depth 1, node 5 has only a right child 7 and node 18 has only a left child 15, so depth 2 collects [7, 15] from left to right with no None placeholders.

Example 3

Input: root = [-5]
Output: [[-5]]

A single-node tree produces one depth containing [-5].

Example 4

Input: root = []
Output: []

An empty tree has zero depths and returns [].

Constraints

  • The tree contains between 0 and 10^5 non-None nodes.
  • Each node value is a 32-bit signed integer (-2^31 <= val <= 2^31 - 1); zero, negative, and duplicate values may occur.
  • Trees are valid acyclic binary trees and may be balanced, sparse, or skewed to depth 10^5.

Step-by-step walkthrough

  1. Understand the input format and goal

    We want to visit a binary tree from top to bottom (depth 0, then depth 1, then depth 2, and so on) and from left to right within each depth, returning a nested list where each inner list holds all values at one depth.

    In the test harness, root is passed as a compact breadth-first list List[Optional[int]] rather than pre-built node objects:

    • root[0] is the root node's value ([] and [None] both represent an empty tree and return []).
    • After root[0], each existing node — in top-to-bottom, left-to-right order — receives two consecutive slots in the list for (left_child, right_child).
    • None marks a missing child, and a missing node receives no child slots of its own.

    Here is how Example 2 ([10, 5, 18, None, 7, 15, None]) and a skewed chain ([1, None, 2, None, 3]) map from flat lists to trees:

    Example 2: [10, 5, 18, None, 7, 15, None]     Skewed chain: [1, None, 2, None, 3]
    
    slots:   0  1   2    3    4   5     6          slots:  0    1   2    3   4
    vals:  [10, 5, 18, None,  7, 15, None]         vals:  [1, None, 2, None, 3]
                \___/   \_____/   \_____/                      \____/   \____/
              10's kids  5's kids  18's kids                 1's kids  2's kids
    
           10          <- depth 0: [10]                    1          <- depth 0: [1]
          /  \                                              \
         5   18        <- depth 1: [5, 18]                   2        <- depth 1: [2]
          \  /                                                \
           7 15        <- depth 2: [7, 15]                     3      <- depth 2: [3]
    

    Notice that node values can repeat and can be 0 or negative, so we must never identify a node by its value or test if entry: instead of if entry is not None:.

  2. Why naive approaches fall short

    Suppose we try to collect one depth at a time by starting at the root for depth = 0, walking down again from the root for depth = 1, and repeating until a depth has no nodes. On a skewed chain of n = 100,000 nodes, there are 100,000 depths, so those repeated walks visit 1 + 2 + ... + 100,000 ≈ 5 × 10^9 nodes (O(n^2) time), which is far too slow.

    A standard breadth-first search (BFS) — visiting nodes layer by layer with a first-in, first-out queue — visits every node once in the exact order 10, 5, 18, 7, 15. However, if we just pop one node at a time in a single loop, nodes from depth d and newly pushed children from depth d + 1 sit in the queue at the same time, giving one flat list [10, 5, 18, 7, 15] instead of [[10], [5, 18], [7, 15]]. We need a clean way to mark where each depth ends.

  3. Key idea: capture the frontier width before popping each depth

    Instead of storing (node, depth) pairs, we can run BFS one whole depth per outer loop pass by maintaining one simple loop invariant:

    • When each while queue: pass begins, queue holds every node of the active depth (left to right) and zero nodes from any deeper layer.
    • Before popping anything, we save level_size = len(queue).
    • We then loop level_size times: pop from the front, append node.val to current_level, and push node.left then node.right to the back of queue.
    Start of depth 1:   queue = [ 5, 18 ]               level_size = 2 (captured!)
                                  ^-- pop 2 times
    
    Pop 5, push 7:      queue = [ 18 | 7 ]              current_level = [5]
                                  ^    ^-- next depth waiting at back
    
    Pop 18, push 15:    queue = [ 7, 15 ]               current_level = [5, 18] (done!)
                                  ^----- now holds ONLY depth 2, left to right
    

    Because we stop after level_size pops, we never pop the newly pushed children during the same round. And because we use collections.deque (a double-ended queue with O(1) popleft()), removing from the front never shifts elements in memory the way list.pop(0) would.

  4. Rebuild the tree from the flat input list

    First, let's decode the flat input list into standard TreeNode objects (val, left, right) — the exact representation most live interviews give you directly.

    To pair each parent node with its two child slots in entries, we keep a parents queue of real TreeNode objects waiting for their children and an integer slot pointing at the next unread entry:

    from collections import deque
    from typing import List, Optional
    
    
    class TreeNode:
        """One node in a binary tree with an integer value and two optional children."""
    
        def __init__(self, val: int):
            self.val = val
            self.left: Optional["TreeNode"] = None
            self.right: Optional["TreeNode"] = None
    
    
    def build_tree(entries: List[Optional[int]]) -> Optional[TreeNode]:
        """Rebuild a binary tree from its level-order list (None marks a missing child)."""
        # An empty list or a missing root slot represents an empty tree.
        if not entries or entries[0] is None:
            return None
    
        root_node = TreeNode(entries[0])
        # parents: deque of real TreeNodes waiting to receive their (left, right) child slots.
        # Missing nodes (None) never enter `parents`, because None nodes get no child slots.
        parents = deque([root_node])
        slot = 1  # index of the next unread entry in `entries`
    
        while slot < len(entries) and parents:
            parent = parents.popleft()
    
            # First slot belongs to parent.left; use `is not None` so value 0 is preserved.
            if entries[slot] is not None:
                left_child = TreeNode(entries[slot])
                parent.left = left_child
                parents.append(left_child)
            slot += 1
    
            # Second slot belongs to parent.right (guarded in case `entries` ends after left).
            if slot < len(entries) and entries[slot] is not None:
                right_child = TreeNode(entries[slot])
                parent.right = right_child
                parents.append(right_child)
            slot += 1
    
        return root_node
    

    Notice two subtle guards in build_tree: - entries[slot] is not None keeps TreeNode(0) intact (0 is falsy in Python, so if entries[slot]: would wrongly skip it). - slot < len(entries) before reading the right child handles lists of even length where the last parent has a left child at the final index and its missing right child was omitted at the end.

  5. Write the level-by-level BFS

    With root_node built, level_order handles the empty-tree base case (return []) and runs the frontier-width BFS loop. Because everything is iterative, a 100,000-node chain never hits Python's recursion limit.

    def level_order(root: List[Optional[int]]) -> List[List[int]]:
        # Phase 1: Decode the judge's flat level-order list into linked TreeNode objects.
        root_node = build_tree(root)
        if root_node is None:
            return []
    
        # levels: output list of lists, e.g. [[8], [4, 12], [10, 14]], one inner list per depth.
        levels: List[List[int]] = []
        # queue: deque of TreeNodes on the active frontier; popleft() is O(1) unlike list.pop(0).
        queue = deque([root_node])
    
        # Phase 2: Breadth-first search, collecting one complete depth level per outer iteration.
        while queue:
            # Freeze the queue size BEFORE pushing children so we pop only the current depth.
            level_size = len(queue)
            current_level: List[int] = []
    
            for _ in range(level_size):
                node = queue.popleft()
                current_level.append(node.val)
    
                # Enqueue left before right so the next depth stays in left-to-right order.
                if node.left is not None:
                    queue.append(node.left)
                if node.right is not None:
                    queue.append(node.right)
    
            levels.append(current_level)
    
        return levels
    
  6. Trace through Example 2 step by step

    Let's trace root = [10, 5, 18, None, 7, 15, None]:

    1. build_tree(root):

      • root_node = TreeNode(10), parents = [10], slot = 1.
      • Pop 10: entries[1] = 5 (10.left = 5), entries[2] = 18 (10.right = 18). parents = [5, 18], slot = 3.
      • Pop 5: entries[3] = None (5.left = None), entries[4] = 7 (5.right = 7). parents = [18, 7], slot = 5.
      • Pop 18: entries[5] = 15 (18.left = 15), entries[6] = None (18.right = None). parents = [7, 15], slot = 7 (loop ends).
    2. BFS rounds in level_order:

    Round   Queue at start   level_size   Popped -> Pushed children     current_level   levels after round
    -----   --------------   ----------   ---------------------------   -------------   ---------------------------
      1     [10]                 1        pop 10 -> push 5, 18          [10]            [[10]]
      2     [5, 18]              2        pop  5 -> push 7              [5, 18]         [[10], [5, 18]]
                                          pop 18 -> push 15
      3     [7, 15]              2        pop  7 -> push nothing        [7, 15]         [[10], [5, 18], [7, 15]]
                                          pop 15 -> push nothing
    Done    [] (loop ends)                                                              returns [[10], [5, 18], [7, 15]]
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    class TreeNode:
        """One node in a binary tree with an integer value and two optional children."""
    
        def __init__(self, val: int):
            self.val = val
            self.left: Optional["TreeNode"] = None
            self.right: Optional["TreeNode"] = None
    
    
    def build_tree(entries: List[Optional[int]]) -> Optional[TreeNode]:
        """Rebuild a binary tree from its level-order list (None marks a missing child)."""
        # An empty list or a missing root slot represents an empty tree.
        if not entries or entries[0] is None:
            return None
    
        root_node = TreeNode(entries[0])
        # parents: deque of real TreeNodes waiting to receive their (left, right) child slots.
        # Missing nodes (None) never enter `parents`, because None nodes get no child slots.
        parents = deque([root_node])
        slot = 1  # index of the next unread entry in `entries`
    
        while slot < len(entries) and parents:
            parent = parents.popleft()
    
            # First slot belongs to parent.left; use `is not None` so value 0 is preserved.
            if entries[slot] is not None:
                left_child = TreeNode(entries[slot])
                parent.left = left_child
                parents.append(left_child)
            slot += 1
    
            # Second slot belongs to parent.right (guarded in case `entries` ends after left).
            if slot < len(entries) and entries[slot] is not None:
                right_child = TreeNode(entries[slot])
                parent.right = right_child
                parents.append(right_child)
            slot += 1
    
        return root_node
    
    
    def level_order(root: List[Optional[int]]) -> List[List[int]]:
        # Phase 1: Decode the judge's flat level-order list into linked TreeNode objects.
        root_node = build_tree(root)
        if root_node is None:
            return []
    
        # levels: output list of lists, e.g. [[8], [4, 12], [10, 14]], one inner list per depth.
        levels: List[List[int]] = []
        # queue: deque of TreeNodes on the active frontier; popleft() is O(1) unlike list.pop(0).
        queue = deque([root_node])
    
        # Phase 2: Breadth-first search, collecting one complete depth level per outer iteration.
        while queue:
            # Freeze the queue size BEFORE pushing children so we pop only the current depth.
            level_size = len(queue)
            current_level: List[int] = []
    
            for _ in range(level_size):
                node = queue.popleft()
                current_level.append(node.val)
    
                # Enqueue left before right so the next depth stays in left-to-right order.
                if node.left is not None:
                    queue.append(node.left)
                if node.right is not None:
                    queue.append(node.right)
    
            levels.append(current_level)
    
        return levels
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of taking group photos of a family tree one generation at a time using a waiting line — a queue (a first-in, first-out structure where newcomers join the back and people step out from the front). You begin with only the root ancestor in line. Before shooting each generation's photo, you count how many people are currently standing in line (level_size). You call forward only that many people for the current photo, and as each person steps up, their left and right children join the back of the line. Because you stop calling people once level_size reaches zero, everyone left standing in line at the end of the round is the entire next generation, already ordered from left to right.

Why do simpler ideas fall short? Walking down from the root repeatedly for depth = 0, then depth = 1, then depth = 2 re-visits upper ancestors over and over, costing roughly n^2 / 2 steps (about 5 billion visits on a 100,000-node chain). Meanwhile, a plain breadth-first search (BFS) — a traversal that explores nodes layer by layer — visits nodes in the right sequence, but without capturing level_size upfront it flattens every generation into [8, 4, 12, 10, 14] instead of [[8], [4, 12], [10, 14]]. And using a plain Python list with pop(0) shifts every remaining element in memory on each removal, degrading wide trees to quadratic time, whereas collections.deque (a double-ended queue supporting O(1) insertions and removals at both ends) pops from the front in constant time.

Let's trace [8, 4, 12, None, None, 10, 14] (Example 1: root 8 has children 4 and 12; 4 is a leaf; 12 has children 10 and 14): 1. Start with queue = [8]. Capture level_size = 1. Pop 8, push 4 and 12. Round 1 appends [8], leaving queue = [4, 12]. 2. Capture level_size = 2. Pop 4 (no children), then pop 12 (push 10 and 14). Round 2 appends [4, 12], leaving queue = [10, 14]. 3. Capture level_size = 2. Pop 10 and 14 (no children). Round 3 appends [10, 14], leaving queue = [], and returns [[8], [4, 12], [10, 14]].

Complexity

Let L be the length of the serialized input list root, n be the number of real nodes (L <= 2n + 1 unless extra trailing Nones were appended), and w be the maximum width (the largest count of nodes on any single depth).

  • Time: O(L) total (O(n) for the tree traversal itself). build_tree reads each slot of root at most once and pushes/pops each node once in parents. Then the BFS pushes and pops each of the n nodes once in queue, performing O(1) work per node via deque.popleft() and deque.append().
  • Space: O(n) total (O(w) for the BFS queue). Storing the rebuilt TreeNode objects and the output levels takes O(n) memory because every node appears once. When the tree is already passed as TreeNode pointers, the extra working space outside the output is just the BFS queue, which is O(w): inside any round, queue holds the unpopped tail of the active depth plus the already-pushed prefix of the next depth, never exceeding two adjacent levels combined (< 2w).

Edge cases

  • Empty tree ([] or [None]): Returns [], never [[]] or [None].
  • Single-node tree ([-5]): Returns [[-5]].
  • Missing nodes consume no child slots: [1, None, 2, None, 3] is a 3-node right-skewed chain returning [[1], [2], [3]], because None slots never reserve child positions.
  • Internal gaps within a depth ([10, 5, 18, None, 7, 15, None]): Returns [[10], [5, 18], [7, 15]]; missing children are omitted rather than stored as None.
  • Trailing None entries ([1, 2, 3, None, None, None, None]): Add no extra empty level at the end.
  • Zero, negative, and duplicate values: Checking is not None preserves 0 as a real node, and storing TreeNode references handles repeated values cleanly.
  • Skewed chain of 100,000 nodes: Produces 100,000 single-element levels iteratively without hitting Python's recursion stack limit (~1,000 frames).

Common mistakes

  • Returning a flat BFS list [8, 4, 12, 10, 14]: Omitting the inner for _ in range(level_size): loop loses the depth boundaries.
  • Re-evaluating len(queue) on every step of the inner loop: Checking a live len(queue) inside a while condition grows the bound as children are appended and swallows deeper levels; always capture level_size = len(queue) before starting the inner loop.
  • Using list.pop(0) instead of deque.popleft(): list.pop(0) shifts every remaining element left in O(w) time per pop, degrading wide trees to O(n * w) time.
  • Returning [[]] or [None] on an empty tree: Enqueueing None before checking whether the root exists creates a bogus inner list.
  • Indexing root like a binary heap (2*i + 1 and 2*i + 2): Heap indexing assumes missing nodes still reserve slots for nonexistent descendants, failing on sparse inputs like [1, None, 2, None, 3].
  • Testing if entries[slot]: instead of if entries[slot] is not None:: Because bool(0) is False, truthiness checks silently drop every node with value 0.

Alternative approaches

  • Direct TreeNode input (standard whiteboard signature): When root is already a TreeNode reference, skip build_tree and run Phase 2 directly in O(n) time and O(w) auxiliary queue space.
  • Two-list frontier swap (current_nodes and next_nodes): Keep a plain Python list of nodes for the active depth, iterate over it to populate both current_values and next_nodes, and reassign current_nodes = next_nodes at the end of each round in O(n) time without needing deque.
  • Depth-first search (DFS) carrying (node, depth): A depth-first search — plunging down a branch before backtracking — can visit node.left before node.right using an explicit stack [(root_node, 0)] and append node.val to levels[depth] (extending levels whenever depth == len(levels)), running in O(n) time and O(h) stack space for height h.

Follow-up questions

  • How can you emit each finished depth lazily without materializing the entire output upfront? Convert level_order into a generator (a Python function that uses yield to produce one item on demand and pause until the caller requests the next) by replacing levels.append(current_level) with yield current_level. On a pre-built TreeNode tree, peak auxiliary memory drops from O(n) for the full nested output down to O(w) for the active frontier queue plus the single yielded level.
  • What adjustment produces alternating left-to-right and right-to-left order across depths? Keep the queue order and child enqueueing (node.left then node.right) completely unchanged, and only flip how values are recorded on odd depths (depth % 2 == 1). Either call current_level.reverse() before appending on odd depths or collect values into a deque using appendleft on odd depths and append on even depths, maintaining O(n) time without scrambling deeper levels.
  • How large can the frontier queue grow on a height-balanced binary tree of n nodes? Although a height-balanced tree has height O(log n), its bottom layer contains roughly half of all nodes in the entire tree. In a perfect binary tree of n = 2^h - 1 nodes, the leaf level alone holds (n + 1) / 2 nodes, so the BFS queue still reaches O(n) size (~n / 2 nodes), whereas a DFS stack on that same balanced tree uses only O(log n) space.

Follow-up questions

Similar questions

More Adobe interview questions

All 29 Adobe questions →