Binary Tree Vertical Order Traversal Problem
Description
LeetCode Problem 314.
Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Example 2:

Input: root = [3,9,8,4,0,1,7]
Output: [[4],[9],[3,0,1],[8],[7]]
Example 3:

Input: root = [1,2,3,4,10,9,11,null,5,null,null,null,null,null,null,null,6]
Output: [[4],[2,5],[1,10,9,6],[3],[11]]
Constraints:
- The number of nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
Solution
Approach: BFS with Column Indexes
Give the root column 0; a left child is one column to the left (col - 1) and a right child one column to the right (col + 1). The answer lists the columns from the smallest to the largest, and inside a column the values must go top to bottom, and left to right on the same row.
A breadth-first search visits the nodes in exactly that order: row by row, and from left to right within a row. So if we append each node's value to its column's list in BFS order, every list is already sorted correctly. A DFS would not work without extra sorting: it can reach a deep node in a column before a shallower one.
- Push
(root, 0)into a queue. While the queue is not empty, pop(node, col), appendnode.valtocolumns[col], and push the children withcol - 1andcol + 1. - Track the smallest and largest column seen. Columns are contiguous (a child is always next to its parent's column), so the answer is
columns[lo], columns[lo + 1], ..., columns[hi], with no sorting needed.
In example 2, nodes 0 and 1 are both in column 0 on the same row, under different parents; BFS visits 0 first because it is further left, as required. An empty tree returns [].
Complexity: O(n) time and O(n) extra space for the queue and the column lists.
from collections import defaultdict, deque
class Solution:
def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if root is None:
return []
columns = defaultdict(list) # column -> values, top to bottom, left to right
lo = hi = 0
queue = deque([(root, 0)]) # BFS visits each row from left to right
while queue:
node, col = queue.popleft()
columns[col].append(node.val)
lo, hi = min(lo, col), max(hi, col)
if node.left:
queue.append((node.left, col - 1))
if node.right:
queue.append((node.right, col + 1))
return [columns[c] for c in range(lo, hi + 1)]