📖 Scenario: Imagine you have a family tree represented as a binary tree. You want to see the family members grouped by their vertical positions when you look at the tree from the front.
🎯 Goal: Build a program that performs vertical order traversal of a binary tree. It groups nodes by their vertical columns and prints the nodes in each vertical column from top to bottom.
📋 What You'll Learn
Create a binary tree using a TreeNode class with val, left, and right properties
Use a queue to perform a breadth-first traversal while tracking horizontal distances
Group nodes by their vertical columns using a dictionary (Map)
Print the nodes grouped by vertical columns in order from leftmost to rightmost
💡 Why This Matters
🌍 Real World
Vertical order traversal helps in visualizing hierarchical data like family trees, organizational charts, or syntax trees in compilers.
💼 Career
Understanding tree traversals and grouping techniques is essential for software engineers working with data structures, databases, and UI rendering.
Progress0 / 4 steps
1
Create the Binary Tree Structure
Create a class called TreeNode with a constructor that takes a number val and initializes left and right as null. Then create a binary tree with root node value 1, left child 2, right child 3, left child of 2 as 4, and right child of 2 as 5.
DSA Typescript
Hint
Define the TreeNode class first, then create the nodes and link them as described.
2
Set Up a Map to Store Vertical Columns
Create a variable called columnTable as a Map<number, number[]> to store arrays of node values grouped by their vertical column index. Also create two variables minColumn and maxColumn initialized to 0 to track the range of columns.
DSA Typescript
Hint
Use new Map() to create columnTable and initialize minColumn and maxColumn to zero.
3
Perform Vertical Order Traversal Using BFS
Create a queue called queue as an array of tuples containing a TreeNode and its column index. Initialize it with [root, 0]. Use a while loop to process nodes from the queue. For each node, add its value to columnTable at the current column. Update minColumn and maxColumn if needed. Add the left child with column - 1 and right child with column + 1 to the queue if they exist.
DSA Typescript
Hint
Use a queue to do breadth-first search. Track each node's column index and update the map and min/max columns accordingly.
4
Print the Vertical Order Traversal Result
Use a for loop from minColumn to maxColumn. For each column, print the array of node values from columnTable joined by ' -> '. Each column's nodes should be printed on a new line.
DSA Typescript
Hint
Loop from minColumn to maxColumn and print the values joined by arrows.
Practice
(1/5)
1. What does Vertical Order Traversal of a binary tree mean?
easy
A. Nodes are grouped by their vertical columns from left to right
B. Nodes are visited level by level from top to bottom
C. Nodes are visited in preorder (root, left, right)
D. Nodes are visited in inorder (left, root, right)
Solution
Step 1: Understand vertical columns in a tree
Vertical order groups nodes by their horizontal distance from the root, called columns.
Step 2: Define vertical order traversal
Nodes in the same vertical column are collected and output from leftmost to rightmost column.
Final Answer:
Nodes are grouped by their vertical columns from left to right -> Option A
Quick Check:
Vertical order = group by columns [OK]
Hint: Think columns from left to right, not levels or preorder [OK]
Common Mistakes:
Confusing vertical order with level order traversal
Thinking vertical order is preorder or inorder traversal
Ignoring horizontal distance concept
2. Which TypeScript data structure is best to store nodes by their vertical column during vertical order traversal?
easy
A. Map
B. Set<number>
C. Array<number>
D. string[]
Solution
Step 1: Identify need to map columns to nodes
We need to store nodes grouped by their column index, so a mapping from column number to list of nodes is required.
Step 2: Choose appropriate TypeScript structure
A Map with keys as column numbers and values as arrays of node values fits perfectly.
Final Answer:
Map<number, number[]> -> Option A
Quick Check:
Map column to node list = Map<number, number[]> [OK]
Hint: Use Map to link column numbers to node arrays [OK]
Common Mistakes:
Using Set which does not store duplicates or order
Using plain arrays without column keys
Using string arrays which don't map columns
3. Given this TypeScript code for vertical order traversal, what is the output?
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val: number) {
this.val = val;
this.left = null;
this.right = null;
}
}
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
function verticalOrder(root: TreeNode | null): number[][] {
if (!root) return [];
const map = new Map();
const queue: [TreeNode, number][] = [[root, 0]];
while (queue.length) {
const [node, col] = queue.shift()!;
if (!map.has(col)) map.set(col, []);
map.get(col)!.push(node.val);
if (node.left) queue.push([node.left, col - 1]);
if (node.right) queue.push([node.right, col + 1]);
}
return Array.from(map.entries())
.sort((a, b) => a[0] - b[0])
.map(entry => entry[1]);
}
console.log(verticalOrder(root));
medium
A. [[7], [3], [1, 5, 6], [2], [4]]
B. [[4], [2], [1, 5, 6], [3], [7]]
C. [[1], [2, 3], [4, 5, 6, 7]]
D. [[4], [2, 5], [1, 6], [3, 7]]
Solution
Step 1: Assign columns to nodes during BFS
Root (1) at col 0; left child (2) at -1; right child (3) at +1; and so on. Nodes grouped by columns:
- -2: 4
- -1: 2
- 0: 1, 5, 6
- 1: 3
- 2: 7
Step 2: Sort columns and output node lists
Sorted columns from left to right: -2, -1, 0, 1, 2. Output arrays accordingly.
Final Answer:
[[4], [2], [1, 5, 6], [3], [7]] -> Option B
Quick Check:
Column grouping matches output D [OK]
Hint: Track column indices during BFS, then sort keys [OK]
Common Mistakes:
Mixing up column indices for left/right children
Not sorting columns before output
Using DFS instead of BFS causing wrong order
4. The following TypeScript code for vertical order traversal has a bug. What is the bug?
function verticalOrder(root: TreeNode | null): number[][] {
if (!root) return [];
const map = new Map();
const queue: [TreeNode, number][] = [[root, 0]];
while (queue.length) {
const [node, col] = queue.pop()!;
if (!map.has(col)) map.set(col, []);
map.get(col)!.push(node.val);
if (node.left) queue.push([node.left, col - 1]);
if (node.right) queue.push([node.right, col + 1]);
}
return Array.from(map.entries())
.sort((a, b) => a[0] - b[0])
.map(entry => entry[1]);
}
medium
A. map.get(col) returns undefined
B. Missing check for null root
C. Using queue.pop() causes DFS instead of BFS traversal
D. Sorting map entries is incorrect
Solution
Step 1: Identify queue operation used
The code uses queue.pop(), which removes the last element, making it a stack (DFS) behavior.
Step 2: Explain impact on vertical order traversal
Vertical order requires BFS (level order) to maintain correct node order per column. Using pop() breaks this order.
Final Answer:
Using queue.pop() causes DFS instead of BFS traversal -> Option C
Quick Check:
pop() = DFS, need shift() for BFS [OK]
Hint: Use shift() for BFS queue, not pop() [OK]
Common Mistakes:
Confusing pop() with shift() in queue
Ignoring traversal order effect on output
Assuming map.get always returns array without check
5. You want to modify vertical order traversal to sort nodes within the same column by their row (depth) and then by value ascending. Which approach is best?
hard
A. Traverse tree using DFS only and collect nodes in order
B. Use a Set per column to avoid duplicates
C. Sort nodes globally after traversal ignoring columns
D. Store nodes as tuples (row, value) per column and sort before output
Solution
Step 1: Understand sorting requirement within columns
Nodes in the same column must be sorted first by their row (depth), then by value ascending.
Step 2: Choose data structure to store row and value
Store tuples (row, value) for each node in the column map, then sort these tuples before output.
Step 3: Explain why other options fail
Set ignores duplicates and order; DFS alone doesn't guarantee order; global sort ignores column grouping.
Final Answer:
Store nodes as tuples (row, value) per column and sort before output -> Option D
Quick Check:
Sort by row and value per column = store tuples and sort [OK]
Hint: Keep (row, value) pairs per column, then sort [OK]
Common Mistakes:
Using Set which loses order and duplicates
Relying on DFS without tracking rows
Sorting all nodes ignoring column grouping
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.