AAlgoLoopSpaced repetition for LeetCode
HARDTree / RecursionLeetCode ↗

Binary Tree Cameras

The key idea

Process the tree bottom-up and label every node with one of three states: not-covered, covered-without-camera, or has-camera. A leaf can never afford a camera (it would waste coverage), so push the decision up: a parent installs a camera only when forced — i.e. when a child reports it is still not covered. This greedy 'install as late and as high as possible' rule is provably optimal.

Problem

You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.

Return the minimum number of cameras needed to monitor all nodes of the tree.

Constraints

Examples

Input: root = [0,0,null,0,0] Output: 1
Input: root = [0,0,null,0,null,0,null,null,0] Output: 2

Complexity

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

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems