AlgoInsight

DSA problem

Binary Tree Vertical Order Traversal

MediumTree Traversal - Level OrderPattern: Tree Traversal - Level Ordertop600FacebookAmazonMicrosoftGoogleBloomberg

Given the root of a binary tree, return the vertical order traversal of its nodes' values. The vertical order assigns each node a column index: the root has column 0, every left child decrements its parent's column by 1, and every right child increments it by 1. Nodes in the same column are reported in the order they are encountered during a level-order BFS (top to bottom; if two nodes share the same row and column the leftmost — i.e. the earlier-enqueued — comes first).

The trick is to combine BFS with a column-keyed multimap. As we BFS the tree we attach a column index to every node we enqueue. For each dequeued node we append its value to the bucket for its column. Because BFS visits all nodes at depth d before any node at depth d + 1, every bucket naturally accumulates its values in top-to-bottom order.

To emit the final answer we just need the columns in ascending order. A TreeMap in Java does this directly; in C++ std::map keeps keys sorted. In Python, JavaScript, and TypeScript we use a hash map plus two trackers minCol and maxCol, then iterate from minCol to maxCol to assemble the result. Time is O(n) for the BFS, plus O(n) or O(n log n) to emit the columns depending on which container we use; space is O(n).

Examples

Example 1
Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation: Columns: 9 at col -1, 3 and 15 at col 0, 20 at col 1, 7 at col 2. Within col 0 node 3 is at depth 0 and 15 at depth 2, so 3 appears first.
Example 2
Input: root = [3,9,8,4,0,1,7]
Output: [[4],[9],[3,0,1],[8],[7]]
Explanation: Five distinct columns from -2 to 2. Column 0 has 3, 0, 1 in that BFS order.
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,9,10],[3,6],[11]]
Explanation: Demonstrates that BFS order, not strict (row, col) sorting, is used to break column ties.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-treebfslevel-orderhash-table

Browse all DSA problems