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: Minimum Coverage Problem00000Original Tree📹With Camera PlacementCoverage AreaMinimum Cameras: 1
Understanding the Visualization
1
Input Tree
Binary tree with nodes that need monitoring
2
Camera Coverage
Each camera monitors parent, self, and children
3
Minimum Cameras
Find optimal placement for full coverage
Key Takeaway
🎯 Key Insight: Use greedy post-order traversal - place cameras only when children need monitoring, ensuring optimal coverage with minimum cameras.
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