Breadth-first search

Scan the Warehouse Shelves

Original & variantBinary Tree Level Order Traversal ↗

The hierarchy allows any number of children and returns named shelves grouped by depth.

01. The question

A warehouse directory has a name and any number of child shelves, not just two. Return the shelf names grouped by depth, preserving the order of children.

Before revealing the idea, predict the result and describe what information you would need to track.

02. Worked example

InputDepot → [A, B, C]; A → [A1, A2]; C → [C1]

Output[["Depot"], ["A", "B", "C"], ["A1", "A2", "C1"]]

  1. Scan Depot and put its three child shelves into the queue.
  2. The next level contains A, B, and C. Add their children in that order.
  3. The final level contains A1, A2, and C1. There are no remaining shelves.

Try your code

Define solve(data, parameter="") and return your result. Your code runs locally, not on a server.

Edit your test cases

Use 1-10 objects with data and an optional string parameter. Expected outputs are computed from the lesson. An optional expected field must be correct.

Input contract & reference code

Example data: {"name":"Depot","children":[{"name":"A","children":[{"name":"A1","children":[]},{"name":"A2","children":[]}]},{"name":"B","children":[]},{"name":"C","children":[{"name":"C1","children":[]}]}]}. Parameter: "". Numeric parameters arrive as strings; convert them with int(parameter) when needed.

The example and generated cases use the question’s exact variant. This checks behavior on a small test batch—not performance on every possible input.

Python runtime notices

Python downloads only when you run code, using compressed runtime assets. Code is not saved or uploaded. Enable JavaScript to run it.

Five-second execution limit per batch. Standard-library Python only; additional packages and network access are unavailable. Stop ends execution without blocking the lesson.

03. The idea

Try sketching your own approach first. What would you track, and why would it work?

Reveal the idea
  1. Put the root into a queue.
  2. Snapshot the queue length at the beginning of each level.
  3. Process exactly that many nodes, collecting their values and adding children for the next level.

04. Watch it happen

Use Step to move slowly, or Play to follow the whole trace. Change a preset or load your own input.

Input & settings

Each shelf has name and children. Unique names: 1-10 characters. Max 20 shelves, 5 levels, 6 shelves per level. Use null for an empty tree.

Red = current item / blue = active window or cells / green = completed work. A value docks at its actual destination; the original input stays unchanged. Positions start at 0.

Working state / what changes

Ready to begin

Enable JavaScript to step through the animation. The worked example and solution below remain readable without it.

Python / why it changes

The line behind the step

from collections import deque

# Each shelf is {"name": str, "children": [shelves]}.
def scan_shelves(root):
    if root is None:
        return []
    queue = deque([root])
    result = []
    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.popleft()
            level.append(node["name"])
            queue.extend(node["children"])
        result.append(level)
    return result
How to use this walkthrough

Hover or focus a control for its label. Play forms the input and follows values into the working state. Step shows one change; Back and the slider restore exact snapshots. Reduced motion uses instant updates. Saved snapshots and sorted heap displays are teaching overhead, not algorithm complexity.

05. Python solution

from collections import deque

# Each shelf is {"name": str, "children": [shelves]}.
def scan_shelves(root):
    if root is None:
        return []
    queue = deque([root])
    result = []
    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.popleft()
            level.append(node["name"])
            queue.extend(node["children"])
        result.append(level)
    return result

06. Cost & edge cases

Time
O(n)
Space
O(w) auxiliary queue space; O(n) output, where w is the largest level
  • An empty warehouse (null/None) returns [].
  • A single shelf returns a single one-name level.
  • Each shelf may have zero, one, or many children. The animation uses unique names to make queue entries unambiguous.

Keep going