All problems

Problem 260

Top View of Binary Tree

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

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, and a right child one column to the right. Looking down from above the tree, you see one node per column: the first node of that column met in level order (the highest one, and the leftmost if two are at the same level). Print the top view from the leftmost column to the rightmost. Do a breadth-first traversal while tracking each node's column, and keep only the first node seen in each column.

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 the top view, space-separated.

Constraints

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

Example input

7
1 2 3 4 5 6 7

Example output

4 2 1 3 7

Explanation

In the full tree 1 2 3 4 5 6 7, the columns from left to right hold 4; 2; 1, 5 and 6; 3; and 7. From above, the highest node of each column is visible: 4, 2, 1, 3 and 7.

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

Previous: Vertical Order Traversal Next: Bottom View of Binary Tree