struct Node {
int data;
Node* left;
Node* right;
Node(int val) : data(val), left(nullptr), right(nullptr) {}
};
// Tree structure:
// 1
// / \
// 2 3
// \ \
// 4 5
// Top view expected: 2 -> 1 -> 3 -> 5
#include <iostream>
#include <map>
#include <queue>
void topView(Node* root) {
if (!root) return;
std::map<int, int> topNode;
std::queue<std::pair<Node*, int>> q;
q.push({root, 0});
while (!q.empty()) {
auto p = q.front(); q.pop();
Node* node = p.first;
int hd = p.second;
if (topNode.find(hd) == topNode.end()) {
topNode[hd] = node->data;
}
if (node->left) q.push({node->left, hd - 1});
if (node->right) q.push({node->right, hd + 1});
}
for (auto it : topNode) {
std::cout << it.second << " -> ";
}
std::cout << "null" << std::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;
}The top view prints the first node encountered at each horizontal distance from the root.
Here, nodes 2, 1, 3, and 5 are visible from the top at horizontal distances -1, 0, 1, and 2 respectively.
Horizontal distance is used to track how far left or right a node is from the root.
Left child decreases hd by 1, right child increases hd by 1.
void topView(Node* root) {
if (!root) return;
std::map<int, int> topNode;
std::queue<std::pair<Node*, int>> q;
q.push({root, 0});
while (!q.empty()) {
auto p = q.front(); q.pop();
Node* node = p.first;
int hd = p.second;
topNode[hd] = node->data; // Bug here: overwrites existing
if (node->left) q.push({node->left, hd - 1});
if (node->right) q.push({node->right, hd + 1});
}
for (auto it : topNode) {
std::cout << it.second << " -> ";
}
std::cout << "null" << std::endl;
}The code overwrites the value for each horizontal distance every time a node is visited.
This causes the bottom-most node at that horizontal distance to be stored, not the top-most.
Horizontal distances and first nodes encountered are:
- hd -2: 3
- hd -1: 5
- hd 0: 10
- hd 1: 15
- hd 2: 18
Nodes 4, 7, and 16 are hidden behind others from top view.
The map keeps keys (horizontal distances) sorted automatically.
This allows printing the top view nodes from leftmost to rightmost in order.