给定一个二叉树,我们在树的节点上安装摄像头。
节点上的每个摄影头都可以监视其父对象、自身及其直接子对象。
计算监控树的所有节点所需的最小摄像头数量。
难点在于递归过程中,节点共有三种状态。
class Solution {
int res = 0;
public int minCameraCover(TreeNode root) {
if(root == null) return 0;
if(helper(root) == 2) res++;
return res;
}
// 0 has
// 1 cover
// 2 not
private int helper(TreeNode root) {
if(root == null) return 1;
int a = helper(root.left);
int b = helper(root.right);
if(a == 2 || b == 2) {res++;return 0;}
if(a == 1 && b == 1) return 2;
if(a == 0 || b == 0) return 1;
return -1;
}
}