We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
// Create a map to store the horizontal distance and the corresponding node data
map<int, int> verticalMap;
// Create a queue for level-order traversal
queue<pair<Node*, int>> levelOrder;
// Initialize the queue with the root and horizontal distance 0
levelOrder.push({root, 0});
while (!levelOrder.empty()) {
Node* current = levelOrder.front().first;
int horizontalDistance = levelOrder.front().second;
levelOrder.pop();
// If this horizontal distance is not in the map, add it to the map
if (verticalMap.find(horizontalDistance) == verticalMap.end()) {
verticalMap[horizontalDistance] = current->data;
}
// Enqueue the left and right children with updated horizontal distances
if (current->left != nullptr) {
levelOrder.push({current->left, horizontalDistance - 1});
}
if (current->right != nullptr) {
levelOrder.push({current->right, horizontalDistance + 1});
}
}
// Print the top view from left to right
for (const auto& entry : verticalMap) {
cout << entry.second << ' ';
}
}
int main() {
// Create a sample binary tree and call topView
Node* root = new Node{1, new Node{2, nullptr, nullptr}, new Node{3, nullptr, nullptr}};
cout << "Top View of Binary Tree: ";
topView(root);
In this version of the code, I've used a map to store the nodes seen at each horizontal distance, ensuring that only the topmost node at each distance is recorded. This simplifies the code and ensures that it works correctly for various binary tree structures.
cout << endl;
Tree : Top View
You are viewing a single comment's thread. Return to all comments →
is this right?
include
include
include
using namespace std;
struct Node { int data; Node* left; Node* right; };
void topView(Node* root) { if (root == nullptr) { return; }
}
int main() { // Create a sample binary tree and call topView Node* root = new Node{1, new Node{2, nullptr, nullptr}, new Node{3, nullptr, nullptr}}; cout << "Top View of Binary Tree: "; topView(root);
In this version of the code, I've used a map to store the nodes seen at each horizontal distance, ensuring that only the topmost node at each distance is recorded. This simplifies the code and ensures that it works correctly for various binary tree structures. cout << endl;
}