Level Order Traversal
Bexley Council stores a small family tree in one line of numbers. The first number is the earliest ancestor. For the person written at position i, their two descendants are written at positions 2i+1 and 2i+2, counting positions from 0. A -1 marks a position where nobody is recorded, and nobody can be recorded below an unrecorded position either. The archive prints the tree one generation at a time.
Task: Print the tree one generation per line, oldest generation first.
Input
A single line holding up to 1000 integers separated by single spaces. Every value except -1 is a person's record number. A -1 means that position holds nobody, which also disqualifies everything beneath it. Positions beyond the end of the line hold nobody.
Output
One generation per line, oldest first. Within a line, the record numbers appear left to right by position, separated by single spaces. Only real people are printed, so -1 never appears in the output. If the first position holds -1, print nothing at all.
Example:
Input:
3 9 20 -1 -1 15 7
Output:
3
9 20
15 7
Sign in to solve this problem
Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.
Sign in