Vertical Order Traversal of Binary Tree in DSA C++ - Time & Space Complexity
We want to understand how the time needed to do vertical order traversal changes as the tree grows.
How does the number of nodes affect the work done to group nodes by their vertical columns?
Analyze the time complexity of the following code snippet.
struct Node {
int data;
Node* left;
Node* right;
};
void verticalOrder(Node* root) {
map<int, vector<int>> nodes;
queue<pair<Node*, int>> q;
q.push({root, 0});
while (!q.empty()) {
auto [node, hd] = q.front(); q.pop();
nodes[hd].push_back(node->data);
if (node->left) q.push({node->left, hd - 1});
if (node->right) q.push({node->right, hd + 1});
}
}
This code visits each node once, grouping nodes by their horizontal distance (hd) from the root.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that visits each node once.
- How many times: Exactly once per node, so n times for n nodes.
As the number of nodes grows, the work grows roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits and insertions |
| 100 | About 100 visits and insertions |
| 1000 | About 1000 visits and insertions |
Pattern observation: The operations grow linearly with the number of nodes.
Time Complexity: O(n log n)
This means the time grows a bit more than linearly because of sorting keys in the map, but mostly it depends on the number of nodes.
[X] Wrong: "The traversal is just O(n) because we visit each node once, so no extra cost."
[OK] Correct: The map stores nodes by horizontal distance and keeps keys sorted, so inserting each node involves a log n cost, making total time O(n log n).
Understanding this complexity helps you explain how tree traversals combined with data structures like maps affect performance, a common topic in interviews.
"What if we used an unordered_map instead of map? How would the time complexity change?"
Practice
Solution
Step 1: Understand vertical order traversal concept
Vertical order traversal groups nodes by their vertical columns, where nodes in the same vertical line share the same horizontal distance from the root.Step 2: Compare with other traversals
Level order visits nodes by depth, preorder and inorder are depth-first traversals, not grouped by vertical columns.Final Answer:
Nodes are grouped by their vertical columns from left to right -> Option DQuick Check:
Vertical order = group by vertical columns [OK]
- Confusing vertical order with level order traversal
- Thinking preorder or inorder is vertical order
- Ignoring horizontal distance concept
Solution
Step 1: Identify need to group nodes by vertical column
We need a structure that maps vertical column indices (integers) to lists of node values.Step 2: Choose appropriate C++ container
std::map maps column indices to vectors of node values, maintaining sorted order of columns automatically.Final Answer:
std::map -> Option CQuick Check:
Map column index to node list = std::map [OK]
- Using vector alone loses column indexing
- Stack or queue do not map keys to values
- Using unordered_map loses column order
1 / \ 2 3 / \ 4 5What is the vertical order traversal output?
Solution
Step 1: Assign horizontal distances (HD) to nodes
Root 1 has HD=0; left child 2 has HD=-1; right child 3 has HD=1; 4 is left of 2 so HD=-2; 5 is right of 3 so HD=2.Step 2: Group nodes by HD and list in order
HD=-2: [4], HD=-1: [2], HD=0: [1], HD=1: [3], HD=2: [5]. Combine left to right: [4, 2, 1, 3, 5].Final Answer:
[4, 2, 1, 3, 5] -> Option AQuick Check:
Vertical order = [4, 2, 1, 3, 5] [OK]
- Mixing order of nodes in same vertical column
- Ignoring horizontal distance for children
- Listing nodes by level order instead
void verticalOrder(Node* root) {
map m;
queue> q;
q.push({root, 0});
while (!q.empty()) {
auto p = q.front(); q.pop();
Node* node = p.first;
int hd = p.second;
m[hd].push_back(node->data);
if (node->left) q.push({node->left, hd - 1});
if (node->right) q.push({node->right, hd + 1});
}
for (auto &x : m) {
for (int val : x.second) cout << val << " ";
}
}
What is the bug in this code?Solution
Step 1: Check for null root before processing
The code assumes root is not null but does not check. If root is nullptr, q.push({root, 0}) pushes null pointer causing runtime error.Step 2: Verify other parts are correct
Using map keeps columns sorted, order of pushing left then right is correct, horizontal distances are updated properly.Final Answer:
It does not handle empty tree (root == nullptr) -> Option AQuick Check:
Missing null root check causes error [OK]
- Ignoring null root causing crash
- Confusing map with unordered_map for order
- Swapping left and right child pushes
Solution
Step 1: Understand requirement to sort nodes by depth per column
We need to group nodes by vertical column and also by their depth (level) to print top to bottom.Step 2: Choose data structure to store nodes by column and depth
Using map> allows mapping column -> depth -> list of nodes, preserving order in both dimensions.Final Answer:
Use map> to store nodes by column and depth -> Option BQuick Check:
Nested map for column and depth sorting [OK]
- Sorting vectors after traversal is inefficient
- Using unordered_map loses order
- Ignoring depth dimension in grouping
Ready to prove it?
Pass the test and this pattern moves unknown
