FunctionRacerProblemsRace

Top View of a Tree

MediumTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. Give every node a column number: the root is column 0, a left child is one column less than its parent, a right child one more. Looking from above, in each column you see the node closest to the root; if two nodes in a column are on the same level, the one that comes first in level order (left to right) wins. Return the visible values from the smallest column to the largest. An empty tree gives [].

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [1,2,3,4,5,6,7]
returns [4,2,1,3,7]

Columns -2..2 hold 4, 2, 1, 3, 7. Column 0 shows 1 (on top of 5 and 6).

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems