Binary Tree Cameras (LeetCode 968): Solution and Explanation

Hard
Dynamic Programming
Tree
Depth First Search
Binary Tree

Place cameras on nodes of a binary tree, where each camera watches its own node, its parent and its children. Return the fewest cameras needed so that every node in the tree is watched.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A brute force tries every subset of nodes as camera positions, which is exponential. A tree DP that tracks, for each node, the best cost for each possible coverage state works in linear time but is fiddly. There is a simpler greedy that follows from looking at the leaves.

A leaf should never hold a camera. A camera on a leaf covers the leaf and its parent, while a camera on the parent covers the leaf, the parent, the parent's other child and the grandparent. The parent placement covers a superset, so it is never worse. Applying that argument bottom up gives the rule: leave nodes uncovered as long as possible, and put a camera on a node only when one of its children would otherwise stay unwatched.

To apply the rule we need information flowing up from children, which means a post-order DFS. Each call reports one of three states for its node: 0 means not covered, 1 means covered without a camera and 2 means it has a camera. A parent with any uncovered child must install a camera. A parent with a camera child is covered for free. A parent whose children are both covered without cameras is left uncovered, hoping its own parent will place a camera. Null children report 1, covered, so they never force a camera on a leaf. If the root ends up uncovered, nobody above it can help, so it gets one final camera.

Approach: Greedy post-order DFS with three states

  1. Define dfs(node) returning 0 (not covered), 1 (covered, no camera) or 2 (has a camera), and keep a counter self.cameras.
  2. For a null node, return 1 so that missing children never force a camera.
  3. Recurse into the left and right children first.
  4. If either child returned 0, place a camera here, increment the counter and return 2.
  5. Else if either child returned 2, this node is covered by that camera, so return 1.
  6. Otherwise both children are covered without cameras, so return 0 and leave the decision to the parent.
  7. After calling dfs(root), add one more camera if the root returned 0, then return the counter.

Step-by-step example

root = [0, 0, null, 0, 0] (root A, left child B, B has two leaf children C and D)
  1. dfs(C): both children are null and return 1, so C is not covered and returns 0. dfs(D) also returns 0.
  2. dfs(B): its children returned 0 and 0, so B gets a camera. cameras = 1 and B returns 2.
  3. dfs(A): the left child returned 2 and the right child (null) returned 1, so A is covered and returns 1.
  4. The root returned 1, not 0, so no extra camera is needed. The answer is 1.

Code: Python, Java, C++

1class Solution:
2    def minCameraCover(self, root: Optional[TreeNode]) -> int:
3        # States: 0 = not covered, 1 = covered (no camera), 2 = has camera
4        self.cameras = 0
5
6        def dfs(node):
7            if not node:
8                return 1  # null nodes are "covered"
9
10            left = dfs(node.left)
11            right = dfs(node.right)
12
13            # If any child is not covered, we must place camera here
14            if left == 0 or right == 0:
15                self.cameras += 1
16                return 2
17
18            # If any child has camera, current node is covered
19            if left == 2 or right == 2:
20                return 1
21
22            # Both children covered but no camera nearby
23            return 0
24
25        # If root is not covered, add one more camera
26        if dfs(root) == 0:
27            self.cameras += 1
28
29        return self.cameras

Time and space complexity

Time

O(n)

Every node is visited exactly once in the post-order traversal and does constant work.

Space

O(h)

The recursion stack goes as deep as the tree height h, which is O(log n) for a balanced tree and O(n) for a skewed one.

Other approaches

Tree DP with three costs per node (time O(n), space O(h))

Return a triple from each node: the minimum cameras if this node has a camera, if it is covered by a child, and if it is not yet covered but its subtree is. Combine children's triples at each parent. It reaches the same answer, generalizes better to weighted camera costs and does not require the greedy proof.

Common mistakes

  • Returning 0 for null nodes, which forces a camera on every leaf and roughly doubles the count.
  • Forgetting the final check at the root. A root that returns 0 has no parent to cover it.
  • Checking the camera case before the uncovered case. If one child has a camera and the other is uncovered, the node still needs a camera.
  • Placing cameras top down, starting at the root, which is not optimal because the root is a poor spot compared to the parents of leaves.

Frequently asked questions

Why is greedy optimal for Binary Tree Cameras?

A camera on a leaf's parent covers everything a camera on the leaf would cover and more. Pushing cameras as high as possible while still covering every child is therefore never worse, and the bottom-up DFS applies that rule at every level.

What do the three states mean?

State 0 means the node is not yet watched, 1 means it is watched by a neighbor but has no camera, and 2 means it holds a camera. The parent decides what to do based on its children's states.

Is this a dynamic programming problem?

It can be solved with tree DP that tracks the cost of each state, which is the safer approach in general. The greedy is a simplification of that DP that works because of the leaf argument.