Tree Levels

Tree Levels

Return the values of the tree grouped by level: index 0 is the root's level, index 1 the next, and so on, each in left-to-right order.

treeLevels(root)

Input format: level-order with x for missing children. Output each level's values space-separated, with levels separated by | (e.g. 3 | 9 20 | 15 7).

Examples

3 9 20 x x 15 7   // → [[3] [9 20] [15 7]]   → "3 | 9 20 | 15 7"
1 2 3              // → [[1] [2 3]]            → "1 | 2 3"
(empty)            // → []                      → ""

Walkthrough

Thinking it through

Plain breadth-first traversal gives you every node in level order as one flat sequence, but it doesn't mark where one level ends and the next begins — that boundary is lost once everything's in one list. This problem asks you to preserve it.

The key realization: the queue's size at the right moment tells you the boundary

In a queue-based BFS, at the instant you're about to start a new level, the queue contains exactly that level's nodes and nothing else — no next-level nodes have been added yet, since those only get enqueued as you process the current level. So checking the queue's length at that exact moment, before dequeuing anything for this round, tells you precisely how many nodes belong to the current level.

Building the algorithm around that invariant

  1. Seed the queue with the root, if the tree isn't empty.
  2. At the start of each round, record the current queue length as this level's size.
  3. Dequeue exactly that many nodes, collecting their values into a fresh list, and enqueue each one's children as you go.
  4. Once you've dequeued that many, append the level's list to your result and start the next round.
  5. Repeat until the queue is empty.

This works because children enqueued during round N always belong to level N+1, and capturing the size before any of those get dequeued draws a hard line between this round's nodes and next round's.

Why this is a natural extension, not a new technique

This is the same queue-based level-order traversal as plain BFS — the only addition is snapshotting the size before each round, turning a flat sequence into level-grouped output with no extra data structure.

Cost

Every node is still enqueued and dequeued once, so total work is proportional to the number of nodes, with the queue bounded by the tree's widest level.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.