medium Binary Tree Vertical Order Traversal
Problem Statement
Given the root of the binary tree, return the 2D list containing the vertical order traversal of the binary tree.
A vertical order traversal of the tree is defined as a top to bottom, column by column traversal.
Note: If two nodes are in the same row and column, keep its order from left to right.
Examples
Example 1:
- Input: A binary tree:
[1,2,3,4,5,6,7] - Expected Output:
[[4], [2], [1,5,6], [3], [7]] - Justification: Nodes 4, 2, 1 with 5 and 6, 3, and 7 are in separate vertical lines. The nodes in each vertical line are listed in the order they appear from top to bottom.

Example 2:
- Input: A binary tree:
[3,9,8,4,0,1,7] - Expected Output:
[[4], [9], [3,0,1], [8], [7]] - Justification: Nodes are grouped based on their vertical positions. Lower nodes in the same vertical line follow the higher ones.

Example 3:
- Input: A binary tree:
[3,null,20,15,7] - Expected Output:
[[3, 15], [20], [7]] - Justification: The tree is skewed to the right. The output reflects the vertical traversal from left to right.

Try it yourself
Try solving this question here:
✅ Solution Binary Tree Vertical Order Traversal
Problem Statement
Given the root of the binary tree, return the 2D list containing the vertical order traversal of the binary tree.
A vertical order traversal of the tree is defined as a top to bottom, column by column traversal.
Note: If two nodes are in the same row and column, keep its order from left to right.
Examples
Example 1:
- Input: A binary tree:
[1,2,3,4,5,6,7] - Expected Output:
[[4], [2], [1,5,6], [3], [7]] - Justification: Nodes 4, 2, 1 with 5 and 6, 3, and 7 are in separate vertical lines. The nodes in each vertical line are listed in the order they appear from top to bottom.

Example 2:
- Input: A binary tree:
[3,9,8,4,0,1,7] - Expected Output:
[[4], [9], [3,0,1], [8], [7]] - Justification: Nodes are grouped based on their vertical positions. Lower nodes in the same vertical line follow the higher ones.

Example 3:
- Input: A binary tree:
[3,null,20,15,7] - Expected Output:
[[3, 15], [20], [7]] - Justification: The tree is skewed to the right. The output reflects the vertical traversal from left to right.

Solution
To solve this problem, we'll use a breadth-first search (BFS) strategy combined with a tracking mechanism for the horizontal positions (or 'columns') of the nodes. BFS is ideal because it naturally explores the tree level by level, ensuring that we process nodes on the same level in the correct order.
We'll use a queue to facilitate the BFS, and a hashmap (or dictionary) to keep track of the nodes' column indices. The key point is to associate each node with its respective column index, allowing us to group nodes that are vertically aligned. We'll also keep track of the minimum and maximum column indices encountered, which will guide us in forming the final output list in the correct left-to-right vertical order.
Step-by-step Algorithm
- Initialize a queue to perform BFS and a hashmap to store node values grouped by their column index.
- Start with the root node in the queue, with a column index of 0.
- Perform
BFS:- Dequeue a node from the queue and record its value in the hashmap under its column index.
- If the node has a
left child, enqueue it with a column index one less than the current node. - If the node has a
right child, enqueue it with a column index one more than the current node. - Update the
minimumandmaximum column indiceswhen necessary.
- After completing BFS, iterate from the minimum to the maximum column index, and append the corresponding list of node values from the hashmap to the output list.
Algorithm Walkthrough
Consider the input [1,2,3,4,5,6,7]. Let's walk through the algorithm:
- Start with root node
1at column index0. - Enqueue left child
2with column index-1, and right child3with column index+1. - Continue BFS:
- For node
2, enqueue its children4and5with column indices-2and0, respectively. - For node
3, enqueue its children6and7with column indices0and+2, respectively.
- For node
- The final column index hashmap looks like:
{-2: [4], -1: [2], 0: [1, 5, 6], 1: [3], 2: [7]}. - Iterating over the column indices from
-2to2, we get the final output:[[4], [2], [1,5,6], [3], [7]].
Code
import java.util.*;
// TreeNode class definition
// class TreeNode {
// int val;
// TreeNode left;
// TreeNode right;
// TreeNode(int x) {
// val = x;
// }
// TreeNode(int x, TreeNode left, TreeNode right) {
// val = x;
// this.left = left;
// this.right = right;
// }
// }
// Pair class to associate a node with its column index
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Map<Integer, List<Integer>> columnTable = new HashMap<>();
Queue<Pair<TreeNode, Integer>> queue = new ArrayDeque<>();
int column = 0;
int minColumn = 0, maxColumn = 0;
// Start BFS with the root node
queue.offer(new Pair<>(root, column));
while (!queue.isEmpty()) {
Pair<TreeNode, Integer> p = queue.poll();
root = p.getKey();
column = p.getValue();
if (root != null) {
// If this column has not been seen before, create a new List
columnTable.putIfAbsent(column, new ArrayList<>());
// Add the node's value to the column's list
columnTable.get(column).add(root.val);
// Update the min and max column indices
minColumn = Math.min(minColumn, column);
maxColumn = Math.max(maxColumn, column);
// Enqueue child nodes with their respective column indices
queue.offer(new Pair<>(root.left, column - 1));
queue.offer(new Pair<>(root.right, column + 1));
}
}
// Construct the final list by combining lists from each column
for (int i = minColumn; i <= maxColumn; i++) {
result.add(columnTable.get(i));
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test cases
// Example 1
TreeNode root1 = new TreeNode(
1,
new TreeNode(2, new TreeNode(4), new TreeNode(5)),
new TreeNode(3, new TreeNode(6), new TreeNode(7))
);
System.out.println(solution.verticalOrder(root1));
// Example 2
TreeNode root2 = new TreeNode(
3,
new TreeNode(9, new TreeNode(4), new TreeNode(0)),
new TreeNode(8, new TreeNode(1), new TreeNode(7))
);
System.out.println(solution.verticalOrder(root2));
// Example 3
TreeNode root3 = new TreeNode(
3,
null,
new TreeNode(20, new TreeNode(15), new TreeNode(7))
);
System.out.println(solution.verticalOrder(root3));
}
}
Complexity Analysis
- Time Complexity: The algorithm's time complexity is
O(N), where N is the number of nodes in the tree. This is because each node is processed exactly once during the BFS. - Space Complexity: The space complexity is also
O(N), as we store all nodes in the hashmap and the queue at
🤖 Don't fully get this? Learn it with Claude
Stuck on Binary Tree Vertical Order Traversal? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Binary Tree Vertical Order Traversal** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Binary Tree Vertical Order Traversal** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Binary Tree Vertical Order Traversal**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Binary Tree Vertical Order Traversal**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.