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 (depth0). Each non-Nonenode, visited from top to bottom and left to right, consumes the next two entries inrootfor its(left_child, right_child)(Noneindicates a missing child; missing children consume no child slots of their own, and trailingNoneentries may be omitted). - Output index
d(0-indexed) contains all values at depthd, 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
0and10^5non-Nonenodes. - 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
Understand the input format and goal
We want to visit a binary tree from top to bottom (depth
0, then depth1, then depth2, 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,
rootis passed as a compact breadth-first listList[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). Nonemarks 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
0or negative, so we must never identify a node by its value or testif entry:instead ofif entry is not None:.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 fordepth = 1, and repeating until a depth has no nodes. On a skewed chain ofn = 100,000nodes, there are100,000depths, so those repeated walks visit1 + 2 + ... + 100,000 ≈ 5 × 10^9nodes (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 depthdand newly pushed children from depthd + 1sit 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.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,queueholds 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_sizetimes: pop from the front, appendnode.valtocurrent_level, and pushnode.leftthennode.rightto the back ofqueue.
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 rightBecause we stop after
level_sizepops, we never pop the newly pushed children during the same round. And because we usecollections.deque(a double-ended queue withO(1)popleft()), removing from the front never shifts elements in memory the waylist.pop(0)would.- When each
Rebuild the tree from the flat input list
First, let's decode the flat input list into standard
TreeNodeobjects (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 aparentsqueue of realTreeNodeobjects waiting for their children and an integerslotpointing 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_nodeNotice two subtle guards in
build_tree: -entries[slot] is not NonekeepsTreeNode(0)intact (0is falsy in Python, soif 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.Write the level-by-level BFS
With
root_nodebuilt,level_orderhandles the empty-tree base case (return []) and runs the frontier-width BFS loop. Because everything is iterative, a100,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 levelsTrace through Example 2 step by step
Let's trace
root = [10, 5, 18, None, 7, 15, None]:-
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).
-
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]]-
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_treereads each slot ofrootat most once and pushes/pops each node once inparents. Then the BFS pushes and pops each of thennodes once inqueue, performingO(1)work per node viadeque.popleft()anddeque.append(). - Space:
O(n)total (O(w)for the BFS queue). Storing the rebuiltTreeNodeobjects and the outputlevelstakesO(n)memory because every node appears once. When the tree is already passed asTreeNodepointers, the extra working space outside the output is just the BFSqueue, which isO(w): inside any round,queueholds 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]], becauseNoneslots 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 asNone. - Trailing
Noneentries ([1, 2, 3, None, None, None, None]): Add no extra empty level at the end. - Zero, negative, and duplicate values: Checking
is not Nonepreserves0as a real node, and storingTreeNodereferences 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 innerfor _ in range(level_size):loop loses the depth boundaries. - Re-evaluating
len(queue)on every step of the inner loop: Checking a livelen(queue)inside awhilecondition grows the bound as children are appended and swallows deeper levels; always capturelevel_size = len(queue)before starting the inner loop. - Using
list.pop(0)instead ofdeque.popleft():list.pop(0)shifts every remaining element left inO(w)time per pop, degrading wide trees toO(n * w)time. - Returning
[[]]or[None]on an empty tree: EnqueueingNonebefore checking whether the root exists creates a bogus inner list. - Indexing
rootlike a binary heap (2*i + 1and2*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 ofif entries[slot] is not None:: Becausebool(0)isFalse, truthiness checks silently drop every node with value0.
Alternative approaches
- Direct
TreeNodeinput (standard whiteboard signature): Whenrootis already aTreeNodereference, skipbuild_treeand run Phase 2 directly inO(n)time andO(w)auxiliary queue space. - Two-list frontier swap (
current_nodesandnext_nodes): Keep a plain Python list of nodes for the active depth, iterate over it to populate bothcurrent_valuesandnext_nodes, and reassigncurrent_nodes = next_nodesat the end of each round inO(n)time without needingdeque. - Depth-first search (DFS) carrying
(node, depth): A depth-first search — plunging down a branch before backtracking — can visitnode.leftbeforenode.rightusing an explicit stack[(root_node, 0)]and appendnode.valtolevels[depth](extendinglevelswheneverdepth == len(levels)), running inO(n)time andO(h)stack space for heighth.
Follow-up questions
- How can you emit each finished depth lazily without materializing the entire output upfront? Convert
level_orderinto a generator (a Python function that usesyieldto produce one item on demand and pause until the caller requests the next) by replacinglevels.append(current_level)withyield current_level. On a pre-builtTreeNodetree, peak auxiliary memory drops fromO(n)for the full nested output down toO(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.leftthennode.right) completely unchanged, and only flip how values are recorded on odd depths (depth % 2 == 1). Either callcurrent_level.reverse()before appending on odd depths or collect values into adequeusingappendlefton odd depths andappendon even depths, maintainingO(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 ofn = 2^h - 1nodes, the leaf level alone holds(n + 1) / 2nodes, so the BFS queue still reachesO(n)size (~n / 2nodes), whereas a DFS stack on that same balanced tree uses onlyO(log n)space.
Follow-up questions
- How can you emit each finished depth lazily without materializing the entire output upfront?
- What adjustment produces alternating left-to-right and right-to-left order across depths?
- How large can the frontier queue grow on a height-balanced binary tree of n nodes?
Similar questions
- Project Roster Builder with Role Quotas
- Lazy Nested List Iterator
- Feasible Task Execution Schedule
- Check for K-Divisible Contiguous Subarray Sum
- Valid Task Schedule from Prerequisites
- Lowest Common Ancestor Requiring Both Targets
More Adobe interview questions
- Diagnosing and Optimizing Full-Stack Web Request Latency Hard
- Partnering with Product Management on High-Stakes Trade-Offs Medium
- Charting Your Medium-Term Engineering Growth Medium Pro
- Live-Updating Product Localization Platform Medium Pro
- Scalable Multimodal Asset Embedding Platform Hard Pro
- Lazy Nested List Iterator Medium Pro
- Distributed Token Frequency Pipeline Without MapReduce Hard Pro
- Feasible Task Execution Schedule Medium Pro
- Valid Task Schedule from Prerequisites Medium Pro
- Highest-Funded Villages and Winning Projects Medium Pro