📖 Scenario: You are working with a binary tree data structure that represents a hierarchy of tasks in a project. You want to view the tasks grouped by their vertical positions when the tree is drawn on paper.
🎯 Goal: Build a program that performs a vertical order traversal of a binary tree. The program will group nodes by their vertical columns and print the nodes in each column from top to bottom.
📋 What You'll Learn
Create a binary tree using node objects with val, left, and right properties
Use a helper variable to track the horizontal distance (column) of each node
Traverse the tree and group nodes by their column in a dictionary
Print the nodes grouped by their vertical columns in order from leftmost to rightmost
💡 Why This Matters
🌍 Real World
Vertical order traversal helps visualize hierarchical data in columns, useful in UI layouts, organizational charts, and parsing expressions.
💼 Career
Understanding tree traversals and grouping data by position is important for software engineers working with data structures, UI rendering, and algorithms.
Progress0 / 4 steps
1
Create the Binary Tree
Create a binary tree with a root node called root. The root node should have val 1, a left child with val 2, and a right child with val 3. The left child of node 2 should be a node with val 4, and the right child of node 2 should be a node with val 5.
DSA Javascript
Hint
Use nested objects to create nodes with val, left, and right properties.
2
Set Up a Map to Store Nodes by Column
Create a variable called columnTable and set it to an empty JavaScript Map. This will store arrays of node values grouped by their column index.
DSA Javascript
Hint
Use new Map() to create an empty map for grouping nodes.
3
Traverse the Tree and Group Nodes by Column
Write a recursive function called traverse that takes a node and its column index. If the node is not null, add its val to the array in columnTable for that column. Then call traverse on the left child with column - 1 and on the right child with column + 1. Finally, call traverse starting from root with column 0.
DSA Javascript
Hint
Use recursion to visit nodes and track their column index. Store values in columnTable.
4
Print the Vertical Order Traversal Result
Print the nodes grouped by their vertical columns in order from the smallest column index to the largest. Use Array.from(columnTable.keys()) to get all column keys, sort them, and then print the arrays of node values for each column separated by spaces.
DSA Javascript
Hint
Sort the column keys and print the node values for each column separated by spaces.
Practice
(1/5)
1. What does Vertical Order Traversal of a binary tree mean?
easy
A. Nodes are visited level by level from top to bottom.
B. Nodes are visited in preorder (root, left, right).
C. Nodes are grouped by their horizontal rows from top to bottom.
D. Nodes are grouped by their vertical columns from left to right.
Solution
Step 1: Understand vertical columns in a binary tree
Vertical order groups nodes by their horizontal distance from the root, called columns.
Step 2: Identify traversal order
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 D
Quick Check:
Vertical order = group by columns [OK]
Hint: Think columns, not rows or preorder traversal [OK]
Common Mistakes:
Confusing vertical order with level order traversal
Thinking vertical order is preorder or inorder traversal
Mixing horizontal rows with vertical columns
2. Which of the following JavaScript code snippets correctly initializes a map to store vertical order nodes by column?
easy
A. const map = new Map();
B. const map = {};
C. const map = new Set();
D. const map = [];
Solution
Step 1: Identify suitable data structure for key-value pairs
We need to map column numbers (keys) to arrays of nodes (values), so Map is ideal.
Step 2: Check each option
const map = new Map(); uses Map which supports keys of any type and preserves insertion order. const map = {}; is an object but less flexible for numeric keys. const map = new Set(); is a Set, which stores unique values without keys. const map = []; is an array, not suitable for key-value mapping.
Final Answer:
const map = new Map(); -> Option A
Quick Check:
Use Map for column to nodes mapping [OK]
Hint: Use Map for flexible key-value storage [OK]
Common Mistakes:
Using Set instead of Map for key-value pairs
Using array instead of Map for mapping columns
Using plain object which may cause key type issues
3. Given the binary tree:
1
/ \
2 3
/ \ \
4 5 6
What is the vertical order traversal output?
medium
A. [[4], [2], [1, 5], [3], [6]]
B. [[1], [2, 3], [4, 5, 6]]
C. [[4, 2], [1, 5, 3], [6]]
D. [[4], [2, 5], [1, 3, 6]]
Solution
Step 1: Assign column indices to nodes
Root (1) is column 0. Left child decreases column by 1, right child increases by 1. So, 4 is at -2, 2 at -1, 1 and 5 at 0, 3 at 1, 6 at 2.
Step 2: Group nodes by columns and list them top to bottom
4. Consider this code snippet for vertical order traversal:
function verticalOrder(root) {
const map = new Map();
function dfs(node, col) {
if (!node) return;
dfs(node.left, col - 1);
dfs(node.right, col + 1);
if (!map.has(col)) map.set(col, []);
map.get(col).push(node.val);
}
dfs(root, 0);
return [...map.values()];
}
What is the main issue with this code?
medium
A. The function does not handle empty trees.
B. Map keys should be strings, not numbers.
C. DFS does not guarantee top-to-bottom order in vertical columns.
D. The code uses recursion incorrectly.
Solution
Step 1: Understand DFS traversal order
DFS explores depth first, so nodes deeper in the tree may be visited before nodes higher up in the same column.
Step 2: Identify vertical order requirement
Vertical order requires nodes in each column to be output top to bottom, which DFS alone does not guarantee.
Final Answer:
DFS does not guarantee top-to-bottom order in vertical columns. -> Option C
Quick Check:
DFS order ≠ vertical top-to-bottom order [OK]
Hint: Use BFS for correct vertical top-to-bottom order [OK]
Common Mistakes:
Assuming DFS preserves vertical order top-to-bottom
Thinking Map keys must be strings
Ignoring empty tree base case (which is handled here)
5. You want to perform vertical order traversal of a binary tree where nodes in the same column and row are sorted by value ascending. Which approach correctly achieves this?
hard
A. Use DFS and store nodes in a map by column only, then output map values.
B. Use BFS with a queue storing nodes with their row and column, then sort nodes by column, row, and value.
C. Traverse tree inorder and group nodes by column index only.
D. Use BFS but ignore row information and output nodes by column only.
Solution
Step 1: Understand sorting requirements
Nodes must be sorted by column, then row (top to bottom), then by node value ascending if same row and column.
Step 2: Choose traversal and data structure
BFS with queue tracks nodes level by level (row), and storing column and row allows sorting by these keys plus value.
Step 3: Why other options fail
DFS does not guarantee row order. Inorder traversal does not track columns properly. Ignoring row info loses sorting order.
Final Answer:
Use BFS with a queue storing nodes with their row and column, then sort nodes by column, row, and value. -> Option B
Quick Check:
BFS + sort by col, row, value = correct order [OK]
Hint: Track row and column with BFS, then sort by col, row, value [OK]
Common Mistakes:
Using DFS which loses row order
Not sorting nodes by value when row and column are same
Ignoring row info in BFS
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.