Advanced graphs and trees · 7 / 15 Exercise Medium

Level-order traversal

Objective

In the level-order traversal the root is visited first, then its children, then the grandchildren, and so on. It is done with a queue (BFS). The first line has the number of nodes n; then come n lines value left right, where left and right are the indexes (from 0) of the children or -1 if there is no child. Node 0 is the root.

Instructions

  • Show one line per level, with the values from left to right separated by spaces.
Input
5
3 1 2
9 -1 -1
20 3 4
15 -1 -1
7 -1 -1
Output
3
9 20
15 7

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise