0
0
DSA C++programming~5 mins

Bottom View of Binary Tree in DSA C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Bottom View of Binary Tree
O(n log n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
10About 10 visits and map updates
100About 100 visits and map updates
1000About 1000 visits and map updates

Pattern observation: The work grows directly with the number of nodes, doubling nodes roughly doubles work.

Final Time Complexity

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.

Common Mistake

[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).

Interview Connect

Understanding how tree traversal combined with data structure operations affects time helps you explain your approach clearly and confidently.

Self-Check

"What if we used an unordered_map instead of map? How would the time complexity change?"