← DiffPush

Top View of Binary Tree

Standard Bar Binary Trees · Medium Problems O(n) · O(n)

The Overpass Headcount Scan

A drone photographs a tree-shaped car-wash lane network from directly overhead. Each lane sits one column left or right of its parent, and taller upstream lanes hide the lanes beneath them in the same column. The traffic office wants the visible lane numbers, reading the photo from leftmost column to rightmost — the first lane encountered from the sky in each column wins.

Input: The root of a binary tree given as a level-order array where null marks a missing child. The root sits at column 0.

Output: Return an array of visible values, one per column, ordered left to right.

Constraints

Examples

Example 1

Input: {"tree":[1,2,3,4,5,6,7]}
Output: [4,2,1,3,7]
Columns -2..2 show 4, 2, the root 1 (which shades 5 and 6), 3, and 7.

Example 2

Input: {"tree":[1,2,3,null,4,null,5]}
Output: [2,1,3,5]
The root sits above 4 in column 0, so 1 stays visible while 4 hides.

Solve this in your browser →

Also on LeetCode ↗