hardTreeGreedyTrees

Binary Tree Cameras

hardTime: O(n)Space: O(h)

Recognize the pattern

minimum cameras to monitor all nodesgreedy from leaves upwardthree states per node

Brute force idea

A straightforward first read of Binary Tree Cameras is this: Try all subsets of nodes for camera placement. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The real unlock in Binary Tree Cameras comes when you notice this: Post-order DFS with three states: 0 = needs monitoring, 1 = has camera, 2 = monitored by child. Leaves return 0 (need monitoring). If any child is 0, place camera (return 1). If any child is 1, this node is covered (return 2). Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Binary Tree Cameras is this: Placing cameras at parents of leaves is always optimal — a camera at a leaf only covers itself and its parent, while a camera at the parent covers the parent, leaf, and grandparent. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

One easy way to drift off course in Binary Tree Cameras is this: Placing cameras at leaves — that's suboptimal. Always place cameras one level above the leaves for maximum coverage. The fix is usually to return to the meaning of each move, not just the steps themselves.

Trees Pattern