1634. Top View Line

A drone flies directly above a binary tree root and photographs it from the top. Place the root at column 0; a left child sits one column to the left of its parent (column - 1) and a right child one column to the right (column + 1). Several nodes can share a column, but from above only one of them is visible: the one reached first in level order, meaning the smallest depth, and among equal depths the leftmost in level-order position.

Return the values of the visible nodes as an array ordered from the leftmost column to the rightmost column. Columns between the leftmost and rightmost are always occupied. A single breadth-first pass runs in O(n) time with O(n) space.

Example 1

Input:
root = [1,2,3,null,4,null,5,null,null,6,7]
Output:
[2,1,3,5,7]
Explanation:

The visible values from left to right are [2, 1, 3, 5, 7].

Example 2

Input:
root = [1,2,3,4,5,6,7]
Output:
[4,2,1,3,7]
Explanation:

The visible values from left to right are [4, 2, 1, 3, 7].

Constraints

1 ≤ nodes ≤ 1000; -1000 ≤ Node.val ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…