All problems

Problem 259

Vertical Order Traversal

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

Problem

Place the nodes of a binary tree in columns: the root is in column 0, a left child is one column to the left of its parent (column - 1), and a right child is one column to the right (column + 1). Print the columns from the leftmost to the rightmost, one line per column. Within a column, list the nodes in level order: higher levels first, and from left to right within the same level. A breadth-first traversal that records each node's column produces exactly this order.

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.

Output

Print one line per column with its values, space-separated.

Constraints

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

Example input

7
3 9 20 null null 15 7

Example output

9
3 15
20
7

Explanation

Node 9 is in column -1. The root 3 and node 15 (left child of 20) are in column 0, with 3 first because it is higher. Node 20 is in column 1 and node 7 in column 2. So the lines are 9, 3 15, 20 and 7.

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

Previous: Sum of Root-to-Leaf Numbers Next: Top View of Binary Tree