Vertical Order Traversal of Binary Tree in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to do vertical order traversal grows as the tree gets bigger.
Specifically, how does the number of nodes affect the work done?
Analyze the time complexity of the following code snippet.
function verticalOrder(root) {
if (!root) return [];
const map = new Map();
const queue = [[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 [...map.entries()].sort((a, b) => a[0] - b[0]).map(entry => entry[1]);
}
This code does a breadth-first search to group nodes by their vertical column index.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop processes each node once.
- How many times: Exactly once per node, so n times if there are n nodes.
As the number of nodes grows, the loop runs once for each node.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loop cycles |
| 100 | About 100 loop cycles |
| 1000 | About 1000 loop cycles |
Pattern observation: The work grows directly with the number of nodes.
Time Complexity: O(n + k log k)
This means the time grows a bit faster than the number of nodes because sorting the columns takes extra time.
[X] Wrong: "The traversal is just O(n) because we visit each node once."
[OK] Correct: We also sort the column keys at the end, which takes O(k log k) time, where k is the number of columns, making total time O(n + k log k). Since k can be up to n, this is O(n log n).
Understanding this time complexity helps you explain how traversal and sorting steps combine, showing you can analyze multi-step algorithms clearly.
"What if we used a balanced tree or heap to keep columns sorted during traversal? How would that affect the time complexity?"
Practice
Vertical Order Traversal of a binary tree mean?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 DQuick Check:
Vertical order = group by columns [OK]
- Confusing vertical order with level order traversal
- Thinking vertical order is preorder or inorder traversal
- Mixing horizontal rows with vertical columns
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 AQuick Check:
Use Map for column to nodes mapping [OK]
- 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
1 / \ 2 3 / \ \ 4 5 6
What is the vertical order traversal output?
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
Columns: -2: [4], -1: [2], 0: [1,5], 1: [3], 2: [6]Final Answer:
[[4], [2], [1, 5], [3], [6]] -> Option AQuick Check:
Column grouping matches answer A [OK]
- Mixing node order within the same column
- Ignoring column indices and grouping by levels
- Swapping left and right child column adjustments
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?
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 CQuick Check:
DFS order ≠ vertical top-to-bottom order [OK]
- Assuming DFS preserves vertical order top-to-bottom
- Thinking Map keys must be strings
- Ignoring empty tree base case (which is handled here)
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 BQuick Check:
BFS + sort by col, row, value = correct order [OK]
- Using DFS which loses row order
- Not sorting nodes by value when row and column are same
- Ignoring row info in BFS
Ready to prove it?
Pass the test and this pattern moves unknown
