Untitled

 avatar
unknown
plain_text
a month ago
1.7 kB
2
Indexable
class Node {
    int data;
    Node left, right;

    Node(int data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

class Solution {
    private int novaccines = 0;

    public int supplyVaccine(Node root) {
        // If the root itself needs a vaccine, increment the count
        if (vaccine(root).equals("want")) {
            novaccines++;
        }
        return novaccines;
    }

    private String vaccine(Node root) {
        if (root == null) {
            return "ok"; // Null nodes are considered as already "ok"
        }

        // Recursively process left and right children
        String left = vaccine(root.left);
        String right = vaccine(root.right);

        // If any child "wants" a vaccine, place one at the current node
        if (left.equals("want") || right.equals("want")) {
            novaccines++;
            return "provide";
        }

        // If any child "provides" a vaccine, the current node is "ok"
        if (left.equals("provide") || right.equals("provide")) {
            return "ok";
        }

        // If neither child "wants" nor "provides", the current node "wants"
        return "want";
    }

    // Driver code (optional for testing)
    public static void main(String[] args) {
        Node root = new Node(0);
        root.left = new Node(0);
        root.right = new Node(0);
        root.left.left = new Node(0);
        root.left.right = new Node(0);

        Solution solution = new Solution();
        System.out.println(solution.supplyVaccine(root)); // Output depends on tree structure
    }
}
Leave a Comment