Bird
Raised Fist0
DSA C++programming

Bottom View of Binary Tree in DSA C++

Choose your learning style10 modes available
Mental Model
We want to see the nodes visible if we look at the tree from the bottom. Each vertical line shows the lowest node at that horizontal distance.
Analogy: Imagine standing under a tree and looking up. The bottom view shows the leaves and branches you can see directly above you, ignoring anything hidden behind.
       20
      /  \
    8     22
   / \      \
  5   3      25
     / \      
    10  14    

Horizontal distances:
-2   -1    0    1    2
 5 ->10 -> 3 ->14 ->25
Dry Run Walkthrough
Input: Binary tree: 20 / \ 8 22 / \ \ 5 3 25 / \ 10 14 Find bottom view
Goal: Find nodes visible from bottom, one per horizontal distance, showing the lowest node at each horizontal distance
Step 1: Start BFS from root (20) at horizontal distance 0
Map: {0: 20}
Queue: [(20,0)]
Why: Initialize with root node at horizontal distance 0
Step 2: Pop (20,0), add left child (8,-1) and right child (22,1)
Map: {0: 20}
Queue: [(8,-1), (22,1)]
Why: Add children with updated horizontal distances
Step 3: Pop (8,-1), add left child (5,-2) and right child (3,0), update map at -1
Map: {-1: 8, 0: 20}
Queue: [(22,1), (5,-2), (3,0)]
Why: Update bottom view for horizontal distance -1 and add children
Step 4: Pop (22,1), add right child (25,2), update map at 1
Map: {-1: 8, 0: 20, 1: 22}
Queue: [(5,-2), (3,0), (25,2)]
Why: Update bottom view for horizontal distance 1 and add child
Step 5: Pop (5,-2), no children, update map at -2
Map: {-2: 5, -1: 8, 0: 20, 1: 22}
Queue: [(3,0), (25,2)]
Why: Update bottom view for horizontal distance -2
Step 6: Pop (3,0), add left child (10,-1) and right child (14,1), update map at 0
Map: {-2: 5, -1: 8, 0: 3, 1: 22}
Queue: [(25,2), (10,-1), (14,1)]
Why: Update bottom view for horizontal distance 0 and add children
Step 7: Pop (25,2), no children, update map at 2
Map: {-2: 5, -1: 8, 0: 3, 1: 22, 2: 25}
Queue: [(10,-1), (14,1)]
Why: Update bottom view for horizontal distance 2
Step 8: Pop (10,-1), no children, update map at -1
Map: {-2: 5, -1: 10, 0: 3, 1: 22, 2: 25}
Queue: [(14,1)]
Why: Update bottom view for horizontal distance -1 with lower node
Step 9: Pop (14,1), no children, update map at 1
Map: {-2: 5, -1: 10, 0: 3, 1: 14, 2: 25}
Queue: []
Why: Update bottom view for horizontal distance 1 with lower node
Result:
Bottom view nodes by horizontal distance:
-2: 5 -> -1: 10 -> 0: 3 -> 1: 14 -> 2: 25
Annotated Code
DSA C++
#include <iostream>
#include <map>
#include <queue>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int val) : data(val), left(nullptr), right(nullptr) {}
};

void bottomView(Node* root) {
    if (!root) return;
    map<int, int> hdNodeMap; // horizontal distance -> node data
    queue<pair<Node*, int>> q; // node and its horizontal distance
    q.push({root, 0});

    while (!q.empty()) {
        auto p = q.front(); q.pop();
        Node* curr = p.first;
        int hd = p.second;

        hdNodeMap[hd] = curr->data; // update bottom view for hd

        if (curr->left) q.push({curr->left, hd - 1});
        if (curr->right) q.push({curr->right, hd + 1});
    }

    for (auto& pair : hdNodeMap) {
        cout << pair.second << " ";
    }
    cout << endl;
}

int main() {
    Node* root = new Node(20);
    root->left = new Node(8);
    root->right = new Node(22);
    root->left->left = new Node(5);
    root->left->right = new Node(3);
    root->right->right = new Node(25);
    root->left->right->left = new Node(10);
    root->left->right->right = new Node(14);

    bottomView(root);
    return 0;
}
q.push({root, 0});
Initialize queue with root at horizontal distance 0
auto p = q.front(); q.pop();
Process next node in BFS order
hdNodeMap[hd] = curr->data;
Update bottom view node for current horizontal distance
if (curr->left) q.push({curr->left, hd - 1});
Add left child with horizontal distance one less
if (curr->right) q.push({curr->right, hd + 1});
Add right child with horizontal distance one more
for (auto& pair : hdNodeMap) { cout << pair.second << " "; }
Print bottom view nodes in order of horizontal distance
OutputSuccess
5 10 3 14 25
Complexity Analysis
Time: O(n) because we visit each node once in BFS
Space: O(n) for the queue and map storing nodes and horizontal distances
vs Alternative: Compared to recursive vertical order traversal, BFS with map is simpler and efficient for bottom view
Edge Cases
Empty tree
Function returns without printing anything
DSA C++
if (!root) return;
Single node tree
Prints the single node as bottom view
DSA C++
q.push({root, 0});
Tree with all nodes on one side
Bottom view shows all nodes in a line
DSA C++
hdNodeMap[hd] = curr->data;
When to Use This Pattern
When asked to find nodes visible from bottom or horizontal view in a tree, use BFS with horizontal distances and update map to track bottom nodes.
Common Mistakes
Mistake: Not updating the map for horizontal distance on every node, so top nodes remain instead of bottom nodes
Fix: Always overwrite the map entry for horizontal distance during BFS to keep the bottom-most node
Summary
Finds the nodes visible when looking at a binary tree from the bottom.
Use when you need to see the lowest nodes at each horizontal distance in a tree.
The key is to track horizontal distances and update the node at each distance as you traverse level by level.

Practice

(1/5)
1. What does the bottom view of a binary tree represent?
easy
A. Nodes visible when the tree is viewed from the bottom
B. Nodes visible when the tree is viewed from the top
C. Nodes visible when the tree is viewed from the left side
D. Nodes visible when the tree is viewed from the right side

Solution

  1. Step 1: Understand the bottom view concept

    The bottom view shows nodes visible when looking from the bottom of the tree, meaning the lowest nodes at each horizontal distance.
  2. Step 2: Compare with other views

    Top view shows nodes visible from above, left and right views show nodes from sides, so bottom view is unique for bottom visibility.
  3. Final Answer:

    Nodes visible when the tree is viewed from the bottom -> Option A
  4. Quick Check:

    Bottom view = nodes visible from bottom [OK]
Hint: Bottom view shows lowest nodes at each horizontal distance [OK]
Common Mistakes:
  • Confusing bottom view with top view
  • Thinking bottom view shows all leaf nodes
  • Mixing bottom view with side views
2. Which of the following C++ STL containers is most suitable to store nodes by their horizontal distance for bottom view calculation?
easy
A. std::vector<int>
B. std::map
C. std::stack<int>
D. std::queue<int>

Solution

  1. Step 1: Identify data structure needs

    We need to map horizontal distances (int) to node values (int) and keep them sorted by horizontal distance.
  2. Step 2: Choose container

    std::map keeps keys sorted and allows key-value pairs, perfect for horizontal distance mapping.
  3. Final Answer:

    std::map -> Option B
  4. Quick Check:

    Use map for sorted key-value pairs [OK]
Hint: Use map to keep horizontal distances sorted [OK]
Common Mistakes:
  • Using vector which is index-based, not key-based
  • Using stack or queue which don't map keys to values
  • Not sorting horizontal distances
3. What is the bottom view output of the following binary tree?

        20
       /  \
     8     22
    / \      \
   5   3      25
      /  \    
     10   14
medium
A. [5, 8, 10, 14, 25]
B. [5, 10, 14, 22, 25]
C. [5, 10, 3, 14, 25]
D. [8, 10, 3, 14, 22]

Solution

  1. Step 1: Assign horizontal distances (HD) to nodes

    Root 20 at HD=0; 8 at HD=-1; 22 at HD=1; 5 at HD=-2; 3 at HD=0; 25 at HD=2; 10 at HD=-1; 14 at HD=1.
  2. Step 2: Determine bottom view nodes by HD

    At HD=-2: 5; HD=-1: 10 (lower than 8); HD=0: 3 (lower than 20); HD=1: 14 (lower than 22); HD=2: 25.
  3. Final Answer:

    [5, 10, 3, 14, 25] -> Option C
  4. Quick Check:

    Bottom view nodes by HD = [5,10,3,14,25] [OK]
Hint: Track horizontal distances and pick lowest nodes [OK]
Common Mistakes:
  • Choosing top nodes instead of bottom nodes
  • Mixing horizontal distances incorrectly
  • Ignoring nodes at same horizontal distance but lower level
4. Consider this code snippet for bottom view calculation. What is the error?

void bottomView(Node* root) {
  if (!root) return;
  std::map hdNodeMap;
  std::queue> q;
  q.push({root, 0});
  while (!q.empty()) {
    auto p = q.front(); q.pop();
    Node* node = p.first;
    int hd = p.second;
    if (hdNodeMap.find(hd) == hdNodeMap.end()) {
      hdNodeMap[hd] = node->data;
    }
    if (node->left) q.push({node->left, hd - 1});
    if (node->right) q.push({node->right, hd + 1});
  }
  for (auto it : hdNodeMap) {
    std::cout << it.second << " ";
  }
}
medium
A. It stores only the first node at each horizontal distance, not the bottom-most
B. It uses queue incorrectly for BFS traversal
C. It does not check for null root
D. It prints nodes in reverse horizontal order

Solution

  1. Step 1: Analyze node storage logic

    The code stores node data only if horizontal distance is not already in map, so it keeps first node encountered at that HD.
  2. Step 2: Understand bottom view requirement

    Bottom view requires the lowest node at each HD, so we must update map with nodes at lower levels, not just first.
  3. Final Answer:

    It stores only the first node at each horizontal distance, not the bottom-most -> Option A
  4. Quick Check:

    Bottom view needs last node at HD, not first [OK]
Hint: Update map with latest node at each horizontal distance [OK]
Common Mistakes:
  • Not updating map for lower level nodes
  • Assuming BFS order guarantees bottom view
  • Ignoring horizontal distance updates
5. Given a binary tree, how would you modify the bottom view algorithm to handle nodes with the same horizontal distance and depth, ensuring the rightmost node is chosen in the bottom view?
hard
A. Use a queue for BFS and update map only if node depth is greater, replacing existing node
B. Use DFS and store only the first node encountered at each horizontal distance
C. Use a stack and update map only if node depth is less than current stored depth
D. Use BFS and update map only if node depth is greater or equal, replacing existing node

Solution

  1. Step 1: Understand the problem with same HD and depth

    When nodes share horizontal distance and depth, bottom view should show the rightmost node.
  2. Step 2: Modify BFS approach

    Use BFS to traverse level by level, and update map if current node's depth is greater or equal to stored node's depth, ensuring rightmost node replaces leftmost at same depth.
  3. Step 3: Implement depth tracking

    Track depth along with horizontal distance, update map accordingly during BFS.
  4. Final Answer:

    Use BFS and update map only if node depth is greater or equal, replacing existing node -> Option D
  5. Quick Check:

    Update map on equal or greater depth for rightmost node [OK]
Hint: Update map if depth >= current to keep rightmost node [OK]
Common Mistakes:
  • Ignoring depth when updating map
  • Using DFS which doesn't guarantee level order
  • Not handling equal depth nodes properly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard