0
0
DSA C++programming

Top View of Binary Tree in DSA C++

Choose your learning style9 modes available
Mental Model
The top view of a binary tree shows the nodes visible when looking from above, ignoring nodes hidden behind others.
Analogy: Imagine standing on a balcony looking down at a garden with trees; you only see the tops of some trees because others block your view behind them.
       1
      / \
     2   3
      \   \
       4   5

Top view shows nodes: 2 -> 1 -> 3 -> 5
Dry Run Walkthrough
Input: Binary tree: 1 / \ 2 3 \ \ 4 5
Goal: Print nodes visible from the top view: nodes that appear first at each horizontal distance from root.
Step 1: Start BFS from root (1) at horizontal distance (hd) = 0
[Queue: (1, hd=0)]
Top view map: {}
Why: We begin from root to explore all nodes level by level with their horizontal distances
Step 2: Dequeue (1, hd=0), add 1 to top view map at hd=0
[Queue: (2, hd=-1), (3, hd=1)]
Top view map: {0: 1}
Why: First node at hd=0 is 1, so it is visible from top
Step 3: Dequeue (2, hd=-1), add 2 to top view map at hd=-1
[Queue: (3, hd=1), (4, hd=0)]
Top view map: {-1: 2, 0: 1}
Why: First node at hd=-1 is 2, so it is visible from top
Step 4: Dequeue (3, hd=1), add 3 to top view map at hd=1
[Queue: (4, hd=0), (5, hd=2)]
Top view map: {-1: 2, 0: 1, 1: 3}
Why: First node at hd=1 is 3, so it is visible from top
Step 5: Dequeue (4, hd=0), hd=0 already has node 1, so skip adding 4
[Queue: (5, hd=2)]
Top view map: {-1: 2, 0: 1, 1: 3}
Why: Node 4 is hidden behind node 1 from top view
Step 6: Dequeue (5, hd=2), add 5 to top view map at hd=2
[Queue: empty]
Top view map: {-1: 2, 0: 1, 1: 3, 2: 5}
Why: First node at hd=2 is 5, so it is visible from top
Result:
Top view nodes in order of hd: 2 -> 1 -> 3 -> 5
Annotated Code
DSA C++
#include <iostream>
#include <queue>
#include <map>
using namespace std;

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

void topView(Node* root) {
    if (!root) return;
    // Map to store first node at each horizontal distance
    map<int, int> top_nodes;
    // Queue stores pairs of node and its horizontal distance
    queue<pair<Node*, int>> q;
    q.push({root, 0});

    while (!q.empty()) {
        auto [node, hd] = q.front();
        q.pop();

        // If hd not seen before, add node data
        if (top_nodes.find(hd) == top_nodes.end()) {
            top_nodes[hd] = node->data;
        }

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

    // Print top view from leftmost to rightmost hd
    for (auto& [hd, val] : top_nodes) {
        cout << val << " -> ";
    }
    cout << "null" << endl;
}

int main() {
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->right = new Node(4);
    root->right->right = new Node(5);

    topView(root);
    return 0;
}
q.push({root, 0});
Start BFS from root with horizontal distance 0
auto [node, hd] = q.front(); q.pop();
Dequeue current node and its horizontal distance
if (top_nodes.find(hd) == top_nodes.end()) { top_nodes[hd] = node->data; }
Add node data if this horizontal distance is seen first time
if (node->left) q.push({node->left, hd - 1}); if (node->right) q.push({node->right, hd + 1});
Add left and right children with updated horizontal distances
for (auto& [hd, val] : top_nodes) { cout << val << " -> "; } cout << "null" << endl;
Print nodes in order from leftmost to rightmost horizontal distance
OutputSuccess
2 -> 1 -> 3 -> 5 -> null
Complexity Analysis
Time: O(n) because we visit each node once during BFS
Space: O(n) for queue and map storing nodes and horizontal distances
vs Alternative: Naive approach might try vertical traversal multiple times causing higher complexity; BFS with map is efficient and clean
Edge Cases
Empty tree
Function returns without printing anything
DSA C++
if (!root) return;
Tree with single node
Prints that single node as top view
DSA C++
q.push({root, 0});
All nodes on one side (left or right)
Prints all nodes in order from top to bottom on that side
DSA C++
if (node->left) q.push({node->left, hd - 1});
if (node->right) q.push({node->right, hd + 1});
When to Use This Pattern
When asked to find nodes visible from top or bottom in a tree, use horizontal distance with BFS and a map to track first or last nodes at each distance.
Common Mistakes
Mistake: Not tracking horizontal distance correctly causing wrong nodes in top view
Fix: Use a queue storing pairs of node and horizontal distance, update hd by -1 for left and +1 for right child
Mistake: Overwriting nodes in map for same horizontal distance
Fix: Only add node to map if horizontal distance is not already present
Summary
Shows nodes visible from above in a binary tree by tracking horizontal distances.
Use when you need to print or find the top view of a binary tree.
The key is to do a level order traversal while recording the first node at each horizontal distance.