Binary Tree Cameras

Given a binary tree, we install cameras on the nodes of the tree.

Each camera at a node can monitor its parent, itself, and its immediate children.

Calculate the minimum number of cameras needed to monitor all nodes of the tree.

Example 1:

Input: [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.

Example 2:

Input: [0,0,null,0,null,0,null,null,0]
Output: 2
Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.

Note:

  1. The number of nodes in the given tree will be in the range [1, 1000].

  2. Every node has value 0.

// Never put cameras on leaf nodes
class Solution {
    boolean isCamera, isCovered;
    int ans;

    public int minCameraCover(TreeNode root) {
        isCamera = false;
        isCovered = false;
        ans = 0;
        helper(root);
        if (!isCovered)
            ans++;
        return ans;
    }
    // Every node sends 2 informations to it's parents
    // 1st -> Is this node a camera ?
    // 2nd -> Is this node covered ?
    public void helper(TreeNode root) {
        if (root.left == null && root.right == null) {
            isCamera = false;
            isCovered = false;
        }
        // Variables for current root node
        boolean isCoveredNode = false, isCameraNode = false;
        if (root.left != null) {
            helper(root.left);
            // If left subtree top node is not covered
            if (!isCovered) {
                ans++;
                isCameraNode = true;
                isCoveredNode = true;
            } else {
                if (isCamera)
                    isCoveredNode = true;
            }
        }
        if (root.right != null) {
            helper(root.right);
            // If right subtree top node is not covered
            if (!isCovered) {
                if (!isCameraNode)
                    ans++;
                isCameraNode = true;
                isCoveredNode = true;
            } else {
                if (isCamera)
                    isCoveredNode = true;
            }
        }
        isCamera = isCameraNode;
        isCovered = isCoveredNode;
    }
}

Last updated