Skip to content
BytePatterns

Top View of a Tree

MediumTrees & BST#bfs#column-index~25m

Problem

Place a binary tree on a grid: the root in column 0, each left child one column left of its parent and each right child one column right. Looking down from above, only the highest node in each column is visible. Return the visible values from the leftmost column to the rightmost; when two nodes tie for highest in a column, the one further left in their level is the one you see.

Examples

Input:  tree = 1, left 2, right 3; 2 has a right child 4,
        4 has a right child 5, 5 has a right child 6
Output: [2, 1, 3, 6]
Why:    4 and 5 hide below 1 and 3; only 6 reaches column 2
Input:  tree = 8, left 4, whose left is 2
Output: [2, 4, 8]
Why:    each node of the left spine opens a new column
Input:  tree = empty
Output: []
Why:    edge case, nothing to see

Hints

0 / 3

Stuck on the idea rather than the code? Vertical Order Traversal covers it.