Untitled

 avatar
unknown
plain_text
a month ago
1.4 kB
2
Indexable
public class SecondLargestBFS {
    public static int findSecondLargestBFS(Node root) {
        if (root == null) return -1; // Tree is empty

        int largest = Integer.MIN_VALUE;
        int secondLargest = Integer.MIN_VALUE;

        // Queue for BFS
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            Node current = queue.poll();

            // Update largest and second largest
            if (current.val > largest) {
                secondLargest = largest;
                largest = current.val;
            } else if (current.val > secondLargest && current.val != largest) {
                secondLargest = current.val;
            }

            // Add children to the queue
            for (Node child : current.children) {
                queue.add(child);
            }
        }

        return secondLargest == Integer.MIN_VALUE ? -1 : secondLargest; // Return -1 if no second largest
    }

    public static void main(String[] args) {
        // Example Tree
        Node n1 = new Node(15);
        Node n2 = new Node(35);
        Node n3 = new Node(10);
        Node n4 = new Node(25);

        n1.children.add(n2);
        n1.children.add(n3);
        n2.children.add(n4);

        System.out.println("Second largest value using BFS: " + findSecondLargestBFS(n1)); // Output: 25
    }
}
Leave a Comment