Binary Tree Cameras
Last updated
Last updated
Input: [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.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.class Solution {
private int count = 0;
public int minCameraCover(TreeNode root) {
int ret = helper(root);
if (ret == 2) return count + 1;
else return count;
}
// return
// 0: covered by child
// 1: has camera, covered
// 2: need to be covered
private int helper(TreeNode root) {
boolean covered = false;
boolean hasCamera = false;
if (root.left == null && root.right == null) {
return 2;
}
if (root.left != null) {
int left = helper(root.left);
if (left == 2) {
hasCamera = true;
covered = true;
} else if (left == 1) {
covered = true;
}
}
if (root.right != null) {
int right = helper(root.right);
if (right == 2) {
hasCamera = true;
covered = true;
} else if (right == 1) {
covered = true;
}
}
if (hasCamera) {
count++;
return 1;
}
if (covered) return 0;
else return 2;
}
}