Problem 261
Bottom 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 up from below the tree, you see one node per column: the last node of that column met in level order (the lowest one, and the rightmost if two are at the same level). Print the bottom view from the leftmost column to the rightmost. Do a breadth-first traversal while tracking each node's column, and overwrite the stored node of a column every time you meet a new one.
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 bottom 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 6 3 7
Explanation
In the full tree 1 2 3 4 5 6 7, column 0 contains 1, then 5 and 6 on the bottom level; 6 is met last, so it is the one seen from below. The other columns hold only 4, 2, 3 and 7. The bottom view is 4 2 6 3 7.