• + 0 comments

    public static void topView(Node root) { if (root == null) { return;

    }
    

    Queue> queue = new LinkedList<>(); // Map to store the first node at each horizontal distance Map map = new TreeMap<>();

        // Start with the root node and horizontal distance 0
        queue.offer(new AbstractMap.SimpleEntry<>(root, 0));
    
        while (!queue.isEmpty()) {
            Map.Entry<Node, Integer> entry = queue.poll();
            Node node = entry.getKey();
            int horizontalDistance = entry.getValue();
    
            // If the horizontal distance is not yet in the map, add it
            if (!map.containsKey(horizontalDistance)) {
                map.put(horizontalDistance, node.data);
            }
    
            // If the node has a left child, enqueue it with horizontal distance - 1
            if (node.left != null) {
                queue.offer(new AbstractMap.SimpleEntry<>(node.left, horizontalDistance - 1));
            }
    
            // If the node has a right child, enqueue it with horizontal distance + 1
            if (node.right != null) {
                queue.offer(new AbstractMap.SimpleEntry<>(node.right, horizontalDistance + 1));
            }
        }
    
        // Print the top view by iterating over the map
        for (int value : map.values()) {
            System.out.print(value + " ");
        }
    }