• + 1 comment

    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; }

    // 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;

    return 0;
    

    }