Binary Tree Cameras
Hard
Topics
You are given the root of a binary tree. A camera placed on a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor every node of the tree.
Example 1
null marks a missing child.Input: root = [0,0,null,0,0] Output: 1
Example 2
Input: root = [0,0,null,0,null,0,null,null,0] Output: 2
Constraints
- 1 <= number of nodes <= 1000
- Node.val == 0.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A camera on a node watches three places: itself, its parent, and its children. We want the fewest cameras covering every node — a minimum dominating set, which is NP-hard on general graphs but tractable on a tree.
The top-down instinct is wrong. Starting at the root and deciding greedily whether to place a camera there has no information: the root's value depends on what the subtrees need, and you cannot know that yet. Every top-down rule you invent fails on some shape.
Reason from the leaves instead. A leaf is never worth covering with its own camera — a camera on the leaf covers the leaf and its parent, while a camera on the parent covers the parent, the leaf, and the leaf's sibling and grandparent. Same cost, strictly more coverage. So cameras belong on parents of leaves, never on leaves.
Generalising that gives the rule: place a camera at a node only when forced, and the only thing that forces it is a child that nothing else will cover. Because the child's own subtree is already settled when we reach the parent, and the only remaining node that could cover it is the parent, this is a safe greedy choice rather than a guess — delaying a camera upward is always at least as good, until a child would be left uncovered, at which point delaying is no longer possible.
Each node reports one of three states to its parent:
0— uncovered: nothing is watching me, my parent must act1— covered, but I have no camera: a child has one2— I have a camera: my parent is covered for free
A null child returns 1, which is the trick that keeps leaves clean: a leaf sees two "covered" children, has no camera of its own, and so correctly reports 0, forcing its parent to place one.
Approach
- Post-order DFS. Recurse into both children before deciding anything about the current node.
- If either child reports
0, place a camera here, increment the count, return2. - Otherwise, if either child reports
2, this node is covered by it — return1. - Otherwise both children are covered but neither has a camera, so nothing watches this node — return
0. - After the recursion, if the root reports
0it has no parent to cover it, so place one final camera.
The order of the checks matters: uncovered children are handled before the has-a-camera case, because a forced placement overrides being covered.
Dry Run
A four-node tree: root A with a single child B, and B has two leaf children C and D. Expected 1.
C (leaf) both children null -> both report 1
no 0 among them, no 2 among them
-> return 0 (uncovered)
D (leaf) same -> return 0 (uncovered)
B children report 0 and 0 -> FORCED
place camera (total 1), return 2
A (root) its child B reports 2 -> covered by B's camera
return 1
root returned 1, not 0, so no extra camera needed
answer 1One camera on B covers all four nodes: itself, both leaves below, and the root above. The leaves reporting 0 is what produced it, and the root needing nothing is the "watches its parent" property paying off.
Complexity
- Time — O(n): each node is visited once and does constant work.
- Space — O(h): the recursion stack, where
his the tree height — O(log n) on a balanced tree and O(n) on a path-shaped one. No table is built; the three states are returned up the stack rather than stored. With up to 1000 nodes the degenerate case is a stack depth of 1000, which is fine here, though an explicit stack would be the answer if the bound were much larger.
Common Pitfalls
- Returning
0for a null child. It must be1(covered) — a node that does not exist needs no camera, and returning0would force a camera on every leaf, roughly doubling the answer. - Checking the has-a-camera case before the uncovered case. A node with one uncovered child and one camera-bearing child must still place a camera; testing
2first wrongly returns "covered" and leaves the other child unwatched. - Forgetting the root fix-up. The root has no parent, so a root reporting
0is genuinely uncovered and needs the extra camera. A single-node tree is the smallest case that exposes it: the answer is 1, not 0. - Working top-down, or deciding the root first. The decision is not computable before the subtrees are known.
- Trying to cover leaves directly. Placing on the parent is never worse and usually better, which is the observation the whole greedy rests on.
- Assuming it needs full DP over three states per node. It does not here — the greedy is provably optimal on trees — but the DP formulation is the right answer if the follow-up adds per-node costs, since then "cheapest" stops coinciding with "fewest".
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def minCameraCover(self, root):
self.cams = 0
def dfs(node):
if not node: return 1
l = dfs(node.left); r = dfs(node.right)
if l == 0 or r == 0:
self.cams += 1; return 2
if l == 2 or r == 2: return 1
return 0
if dfs(root) == 0: self.cams += 1
return self.camsimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int minCameraCover(TreeNode root) {
cams = 0;
if (dfs(root) == 0) cams++;
return cams;
}
int cams;
private int dfs(TreeNode node) {
if (node == null) return 1;
int l = dfs(node.left), r = dfs(node.right);
if (l == 0 || r == 0) {
cams++;
return 2;
}
if (l == 2 || r == 2) return 1;
return 0;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int minCameraCover(TreeNode* root) {
int cams = 0;
function<int(TreeNode*)> dfs = [&](TreeNode* node) -> int {
if (!node) return 1;
int l = dfs(node->left), r = dfs(node->right);
if (l == 0 || r == 0) {
cams++;
return 2;
}
if (l == 2 || r == 2) return 1;
return 0;
};
if (dfs(root) == 0) cams++;
return cams;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var minCameraCover = function(root) {
let cams = 0;
const dfs = (node) => {
if (!node) return 1;
const l = dfs(node.left), r = dfs(node.right);
if (l === 0 || r === 0) {
cams++;
return 2;
}
if (l === 2 || r === 2) return 1;
return 0;
};
if (dfs(root) === 0) cams++;
return cams;
};