• + 0 comments

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

    // A class to store node and its horizontal distance (hd)
    class QueueNode {
        Node node;
        int hd;
    
        QueueNode(Node node, int hd) {
            this.node = node;
            this.hd = hd;
        }
    }
    
    Queue<QueueNode> queue = new LinkedList<>();
    Map<Integer, Integer> topViewMap = new TreeMap<>(); // TreeMap to sort by HD
    
    queue.add(new QueueNode(root, 0));
    
    while (!queue.isEmpty()) {
        QueueNode current = queue.poll();
        int hd = current.hd;
        Node node = current.node;
    
        // Only add to map if this HD hasn't been seen yet
        if (!topViewMap.containsKey(hd)) {
            topViewMap.put(hd, node.data);
        }
    
        // Enqueue left child with HD-1
        if (node.left != null) {
            queue.add(new QueueNode(node.left, hd - 1));
        }
    
        // Enqueue right child with HD+1
        if (node.right != null) {
            queue.add(new QueueNode(node.right, hd + 1));
        }
    }
    
    // Print the top view in left-to-right order (sorted HD)
    for (Map.Entry<Integer, Integer> entry : topViewMap.entrySet()) {
        System.out.print(entry.getValue() + " ");
    }
    

    }