Binary Trees Breadth first: level by level
377. Top View of a Binary Tree
You are given root, the root node of a binary tree. Every node has a column and a row. The root is in
column 0, a left child is one column to the left of its parent, and a right child is one column to the
right. The row is the node's depth: the root is in row 0, its children in row 1, and so on.
Picture yourself looking down on the tree from above. In each column you see only the highest node, the one with the smallest row, and it hides the nodes below it. Return the values of the nodes you see, one per column, from the leftmost column to the rightmost.
Sometimes two nodes in a column are both the highest. Then you see the one that comes first when their row is read from left to right, as the examples write it. Example 2 has such a tie.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [8, 3, 10, 1, 6, null, null, null, null, 4, 7, null, null, null, 14]
[1,3,8,10,14]Explanation: The columns run from −2 to 2. 6, 4 and 7 are hidden by 8, 3 and 10, which sit higher in the same columns. 14 is deep inside the tree, but it is the only node in column 2, so you see it.
Example 2
Input: root = [1, 2, 3, null, 4, 7, null, null, 5, null, 8, null, 6, null, 9]
[2,1,3,6]Explanation: 6 and 9 are both in row 4 and column 2, and nothing in column 2 is higher. Row 4 reads 6, then 9, from left to right, so you see 6. In the other columns, 2, 1 and 3 hide every node below them.
Example 3
Input: root = [-1000000000, 1000000000, null, null, -5]
[1000000000,-1000000000]Explanation: 1000000000 is alone in column −1. −5 is in column 0, below the root, so the root hides it.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
Clarifying questions
What you would ask an interviewer before writing any code.