Post-order states
Time O(n) Space O(h)null → 2. If any child is 0 → camera here (1). Else if any child is 1 → 2. Else → 0. At the root, a 0 needs one more camera.
class Solution {
private int cameras = 0;
public int minCameraCover(TreeNode root) {
return state(root) == 0 ? cameras + 1 : cameras;
}
private int state(TreeNode n) {
if (n == null) return 2;
int l = state(n.left), r = state(n.right);
if (l == 0 || r == 0) { cameras++; return 1; }
if (l == 1 || r == 1) return 2;
return 0;
}
}Verdict: Greedy, justified by the tree structure.