Skip to content
mlmentorship

Freeze the current frontier before adding the next level

Capture one queue boundary, preserve depth order, then select or reduce each complete level.

Published · 9 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Freeze the current frontier before adding the next level

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. The root of a finite binary tree whose nodes have a value and optional left and right children. Output. Return one list of values per depth, starting with the root's level. Rules. Within each level, preserve the nodes' left-to-right order. Missing children contribute no output value or placeholder. Assume no shared nodes or cycles. Leave the tree unchanged; an empty tree returns []. Example. A root 3 has children 9 and 20; node 20 has children 15 and 7. Return [[3], [9, 20], [15, 7]], not one flattened list. Its compact level-order input notation is [3, 9, 20, null, null, 15, 7].

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Snapshotting the queue length separates the current tree level from children appended for the next level.

Problem trace

Freeze this level's queue length before adding the next level

Worked example: freeze the current level before enqueueing its childrenA and B start this illustrative level. A appends A1 and A2; B is a leaf. Process exactly A and B, then leave the new children for the next level.New queue entries do not renew thecurrent level budgetFreeze two entries for this levelAB2 current-level entries remainProcess A; append next-level childrenBA1A21 current-level entries remainProcess leaf B; stop this levelA1A20 current-level entries remain
Read it this way: A and B start this illustrative level. A appends A1 and A2; B is a leaf. Process exactly A and B, then leave the new children for the next level. After A appends two children, does the current level budget become the new queue length three?
Full interview answer 9 min read

Return a binary tree’s values grouped by depth, with each level listed from left to right.

Problem

Input. The root of a finite binary tree whose nodes have a value and optional left and right children.

Output. Return one list of values per depth, starting with the root’s level.

Rules. Within each level, preserve the nodes’ left-to-right order. Missing children contribute no output value or placeholder. Assume no shared nodes or cycles. Leave the tree unchanged; an empty tree returns [].

Example. A root 3 has children 9 and 20; node 20 has children 15 and 7. Return [[3], [9, 20], [15, 7]], not one flattened list. Its compact level-order input notation is [3, 9, 20, null, null, 15, 7].

Picture

Imagine a boundary in the queue between this level and the children being added for the next. At each outer-loop start, the queue contains exactly one complete level. Capture its size before appending anything.

Frozen sizeValues removedQueue after those removals
13[9,20]
29,20[15,7]
215,7[]

Problem trace

Freeze this level's queue length before adding the next level

Input and goalReturn tree values one level at a time.
Queue the rootFor tree [3,9,20,null,null,15,7], initialize answer = [] and queue = [3]. The drawn edges show 3 -> 9, 3 -> 20, 20 -> 15, and 20 -> 7.
queueState[3]answer[]
node 3
queued
queue state
[3]
answer
[]

Recognize it
Use this BFS form when a tree answer is grouped by depth, processed left-to-right by level, or must compute one aggregate per level rather than one flat visitation order.
Keep true
At each while-loop start, the queue contains exactly one complete next level in left-to-right order. Iterating the captured length consumes only that level while appending its children for the following level.
Reuse it
Capture the frontier size before expanding it whenever output or timing is grouped by BFS depth; this transfers to right-side view, level averages, shortest unweighted paths, and wave simulations.
For tree [3,9,20,null,null,15,7], initialize answer = [] and queue = [3]. The drawn edges show 3 -> 9, 3 -> 20, 20 -> 15, and 20 -> 7. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why do 15 and 7 wait for the next level even though they are already in the queue?
Reference drawing

Problem trace

Freeze this level's queue length before adding the next level

Worked example: freeze the current level before enqueueing its childrenA and B start this illustrative level. A appends A1 and A2; B is a leaf. Process exactly A and B, then leave the new children for the next level.New queue entries do not renew thecurrent level budgetFreeze two entries for this levelAB2 current-level entries remainProcess A; append next-level childrenBA1A21 current-level entries remainProcess leaf B; stop this levelA1A20 current-level entries remain
Execution trace
Input and goalReturn tree values one level at a time.
Queue the rootFor tree [3,9,20,null,null,15,7], initialize answer = [] and queue = [3]. The drawn edges show 3 -> 9, 3 -> 20, 20 -> 15, and 20 -> 7.
queueState[3]answer[]
node 3
queued
queue state
[3]
answer
[]

Recognize it
Use this BFS form when a tree answer is grouped by depth, processed left-to-right by level, or must compute one aggregate per level rather than one flat visitation order.
Keep true
At each while-loop start, the queue contains exactly one complete next level in left-to-right order. Iterating the captured length consumes only that level while appending its children for the following level.
Reuse it
Capture the frontier size before expanding it whenever output or timing is grouped by BFS depth; this transfers to right-side view, level averages, shortest unweighted paths, and wave simulations.
For tree [3,9,20,null,null,15,7], initialize answer = [] and queue = [3]. The drawn edges show 3 -> 9, 3 -> 20, 20 -> 15, and 20 -> 7. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why do 15 and 7 wait for the next level even though they are already in the queue?
Read it this way: A and B start this illustrative level. A appends A1 and A2; B is a leaf. Process exactly A and B, then leave the new children for the next level. After A appends two children, does the current level budget become the new queue length three?

During a level, the queue can mix unprocessed current nodes with already discovered next-level nodes. The captured count prevents consuming those children too early. Appending left before right preserves the requested order.

Code

This complete reference includes its node definition. range(len(queue)) evaluates the length once, before the loop body changes the queue.

from __future__ import annotations
from collections import deque
from dataclasses import dataclass

@dataclass(eq=False, slots=True)
class TreeNode:
   val: int
   left: TreeNode | None = None
   right: TreeNode | None = None

def level_order(root: TreeNode | None) -> list[list[int]]:
   if root is None:
      return []

   answer: list[list[int]] = []
   queue = deque([root])

   while queue:
      level = []
      for _ in range(len(queue)):
         node = queue.popleft()
         level.append(node.val)
         if node.left:
            queue.append(node.left)
         if node.right:
            queue.append(node.right)
      answer.append(level)
   return answer

Each node is queued and removed once: time. The queue uses auxiliary space, where is the widest level. It may hold parts of two adjacent levels, still within a constant multiple of . The returned lists separately occupy space.

Failure Check

Consuming until the queue empties inside one level also consumes newly appended children. The source tree then collapses into [3,9,20,15,7], losing the depth partition. Graph inputs need a separate discovered-state contract.

Select One Value

New task: Return the visible right-side value at each depth.

Picture and change: Keep the same depth partition, then select the final left-to-right value. Place this wrapper after the reference above.

def right_side_values(root):
   return [level[-1] for level in level_order(root)]

Check: The source returns [3,20,7]; an empty tree returns []. The wrapper still materializes all levels temporarily: peak storage, not just its returned values.

Use when: One selected value per level is enough.

Reduce Each Level

New task: Return one sum per depth.

Picture and change: Keep the partition and add each level’s values.

def level_sums(root):
   return [sum(level) for level in level_order(root)]

Check: The source returns [3,29,22]. Negative and zero values also contribute normally. Both wrappers take time and leave input links unchanged. Both retain the reference’s temporary level materialization. A fused version could accumulate within each frozen frontier instead.

Use when: Only an aggregate per level is required.

Transfer Check

Why not replace the FIFO queue with a stack while keeping this reasoning?

Answer

A stack can visit newly added descendants before remaining siblings. It does not preserve this complete next-depth frontier without additional state. Compare subtree heights for a different traversal contract.