Binary Trees Breadth first: level by level
372. Vertical Order Traversal of a Binary Tree
You are given root, the root node of a binary tree. Every node has a place in a grid, given by a row and a
column. The root is at row 0, column 0. If a node is at row r and column c, its left child is at row
r + 1, column c - 1, and its right child is at row r + 1, column c + 1. So the row is the node's
depth, and columns can be negative.
Return the values of the nodes column by column: a list with one list for each column, from the leftmost column to the rightmost. Each column's list goes from the top row down. Two nodes can sit in the same row and the same column; those are listed by value, smallest first.
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 = [6, 3, 9, -2, 7, 4, 12]
[[-2],[3],[6,4,7],[9],[12]]Explanation: The columns run from −2 to 2. Column 0 holds 6 at row 0, then 7 and 4, which are both at row 2. They share a row and a column, so the smaller value, 4, comes first.
Example 2
Input: root = [5, 1, null, null, -3, 2]
[[1,2],[5,-3]]Explanation: 1 and 2 are in column −1, at rows 1 and 3. 5 and −3 are in column 0, at rows 0 and 2. −3 is smaller than 5, but it sits lower, so it comes after 5.
Example 3
Input: root = [1000000000, null, -1000000000, null, 1000000000]
[[1000000000],[-1000000000],[1000000000]]Explanation: Each node is a right child, one column to the right of its parent, so every column holds one node.
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.