All problems

Problem 145

Binary Tree Level Order Traversal

Medium · 20 pts · Tree, Breadth-First Search, Binary Tree

Problem

You are given a binary tree. Print its values level by level: the root on the first line, its children on the second line, their children on the third, and so on. Within each level, list the nodes from left to right. Use breadth-first search with a queue. Process the tree one level at a time: note how many nodes are in the queue, take exactly that many out (these form the current level), and add their children for the next level.

Input

First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses).

Output

Print one line per level with that level's values, space-separated.

Constraints

1 <= number of nodes <= 10000; -1000 <= value <= 1000

Example input

7
3 9 20 null null 15 7

Example output

3
9 20
15 7

Explanation

The root 3 forms the first level. Its children 9 and 20 form the second level. The children of 20, which are 15 and 7, form the third. So the lines are 3, then 9 20, then 15 7.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Binary Tree Postorder Traversal Next: Invert Binary Tree