Level by level

A binary tree is given in level order, with null for a missing child (the children of a missing node are not listed). Print its values level by level.

What to build

A program that prints the values of each level of the tree, from top to bottom and left to right.

Requirements

  • Print one line per level, with the values separated by spaces.
  • Use a queue (breadth-first), not recursion.

Input

One line: the level-order list. The first entry is not null.

Output

One line per level.

Constraints

1 ≤ entries ≤ 10⁴.

Example

Input:

3 9 20 null null 15 7

Output:

3
9 20
15 7

Why it works

A queue yields nodes in the order they were discovered, which is level by level. Taking len(queue) nodes per round separates one level from the next.

Examples

Example 1 · Input
3 9 20 null null 15 7
Expected output
3
9 20
15 7
Example 2 · Input
1
Expected output
1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Rebuild the tree with a queue: each node takes the next two entries as its children.

Hint 2

Then traverse with a queue again, and in each round take exactly len(queue) nodes: that is one level.

Hint 3

Print one level per line.

Solution

Show one correct solution (try it yourself first)
from collections import deque

values = input().split()
root = [values[0], None, None]
queue = deque([root])
i = 1
while queue and i < len(values):
    node = queue.popleft()
    for side in (1, 2):
        if i < len(values) and values[i] != "null":
            node[side] = [values[i], None, None]
            queue.append(node[side])
        i += 1
queue = deque([root])
while queue:
    level = []
    for _ in range(len(queue)):
        node = queue.popleft()
        level.append(node[0])
        for child in (node[1], node[2]):
            if child:
                queue.append(child)
    print(*level)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Binary trees →