• + 0 comments

    Solution Steps: 1 - Perform a level-order traversal of the tree. 2- Keep track of the horizontal distance of each node from the root. For the root node, the horizontal distance is 0. For the left child, the horizontal distance decreases by 1, and for the right child, it increases by 1. 3 - Use a map or a dictionary to store the nodes at each horizontal distance. 4 - Traverse the tree and update the map with the first node encountered at each horizontal distance. 5 - Finally, print the values of the nodes stored in the map.

    // c++
    
    void topView(Node* root) {
        if (!root) return;
        queue<pair<Node*, int>> q;
        map<int, int> mp;
        q.push({ root, 0 });
        while (q.size()) {
            auto temp = q.front();
            q.pop();
            int horizontal_distance = temp.second;
            Node* node = temp.first;
            if (!mp[horizontal_distance]) {
                mp[horizontal_distance] = node->data;
            }
            if (node->left) {
                q.push({ node->left, horizontal_distance - 1 });
            }
            if (node->right) {
                q.push({ node->right, horizontal_distance + 1 });
            }
        }
        for (auto node : mp) {
            cout << node.second << ' ';
        }
    }
    

    Explanation: - We traverse the tree level by level using a queue. - At each level, we update the horizontal distance of each node and store the first encountered node at each horizontal distance in a dictionary. - Finally, we print the nodes stored in the dictionary, which represent the top view of the tree.