Bottom View of Binary Tree in DSA C++ - Time & Space Complexity
We want to understand how the time needed to find the bottom view of a binary tree changes as the tree grows.
How does the number of nodes affect the work done to get the bottom view?
Analyze the time complexity of the following code snippet.
void bottomView(Node* root) {
if (!root) return;
map hdNodeMap; // horizontal distance to node data
queue> q;
q.push({root, 0});
while (!q.empty()) {
auto nodePair = q.front(); q.pop();
Node* node = nodePair.first;
int hd = nodePair.second;
hdNodeMap[hd] = node->data; // overwrite for bottom view
if (node->left) q.push({node->left, hd - 1});
if (node->right) q.push({node->right, hd + 1});
}
for (auto& [hd, val] : hdNodeMap) {
cout << val << " ";
}
}
This code finds the bottom view of a binary tree by level order traversal and tracking horizontal distances.
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 in the tree (n times).
- Inside the loop, updating the map is done for each node.
As the number of nodes (n) increases, the number of times we visit nodes and update the map grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits and map updates |
| 100 | About 100 visits and map updates |
| 1000 | About 1000 visits and map updates |
Pattern observation: The work grows directly with the number of nodes, doubling nodes roughly doubles work.
Time Complexity: O(n log n)
This means the time grows a bit more than linearly because each node insertion into the map takes logarithmic time.
[X] Wrong: "The time complexity is O(n) because we visit each node once."
[OK] Correct: Although each node is visited once, updating the map takes O(log n) time, so total time is O(n log n).
Understanding how tree traversal combined with data structure operations affects time helps you explain your approach clearly and confidently.
"What if we used an unordered_map instead of map? How would the time complexity change?"