Binary Tree Cameras

Minimum cameras to monitor all nodes — greedy bottom-up with three states (covered, has camera, uncovered).

Hard
Time O(n) Space O(h)
LeetCode
3 min read
dp tree greedy

Problem#

A camera at a node covers itself and its parent and children. Return the minimum number of cameras needed to cover all nodes.

Examples#

  • [0,0,null,0,0]1

Constraints#

  • 1 <= n <= 1000.

Approach#

DFS returning a state: 0 = needs coverage, 1 = covered (by child), 2 = has camera. If any child returns 0, this node must hold a camera (count++, return 2). If any child returns 2, this node is already covered (return 1). Else 0 (covered by neither side; parent must cover us).

Solution#

Binary Tree Cameras
class Solution {
public:
int minCameraCover(TreeNode* root) {
int cameras = 0;
function<int(TreeNode*)> dfs = [&](TreeNode* n) -> int {
if (!n) return 1; // null counts as covered
int l = dfs(n->left), r = dfs(n->right);
if (l == 0 || r == 0) { ++cameras; return 2; }
if (l == 2 || r == 2) return 1;
return 0;
};
if (dfs(root) == 0) ++cameras;
return cameras;
}
};

Editorial#

Three-state DFS is the cleanest framing. Bottom-up greedy chooses to place a camera at the lowest level needed. Placing cameras at parents of leaves (rather than leaves themselves) is optimal because a parent-camera covers 3 nodes vs a leaf-camera’s 2.

Complexity#

  • Time: O(n).
  • Space: O(h).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.