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.

Input & Output

Example 1 — Simple Tree
$ Input: root = [0,0,null,0,0]
Output: 1
💡 Note: Place one camera at root node 0. It monitors itself and both children at level 1. The grandchildren at level 2 are monitored by their parents.
Example 2 — Single Path
$ Input: root = [0,0,null,0,null,0,null,null,0]
Output: 2
💡 Note: Two cameras needed - one can be placed optimally to cover 3 nodes each, requiring 2 cameras total for this linear path.
Example 3 — Single Node
$ Input: root = [0]
Output: 1
💡 Note: Single node tree requires exactly one camera to monitor itself.

Constraints

  • The number of nodes in the tree is in the range [1, 1000].
  • Node.val == 0

Visualization

Tap to expand
Binary Tree Cameras INPUT 0 0 0 0 root = [0,0,null,0,0] 5 nodes in binary tree ALGORITHM STEPS 1 DFS Post-Order Process children first 2 Track States 0=need, 1=covered, 2=camera 3 Greedy Choice Place camera at parent of leaf 4 Check Root Add camera if root needs one State Transitions NEED (0) COVERED(1) CAM (2) Child needs --> Parent gets camera Child has camera --> Parent covered Both covered --> Parent needs FINAL RESULT OK OK OK Camera node Monitored node Output: 1 1 camera monitors all 5 nodes Key Insight: Greedy strategy: Place cameras at parents of leaves, not at leaves themselves. Each camera covers 3 levels (parent + self + children), maximizing coverage efficiency. TutorialsPoint - Binary Tree Cameras | Greedy DFS with State Tracking
Asked in
Google 15 Facebook 12 Amazon 8
89.5K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen