Python 0968.py
class Solution:
def minCameraCover(self, root: Optional[TreeNode]) -> int:
result = 0
# constants (return values of deeper())
unknown = -1
monitored = 0
camera = +1
def deeper(node):
if not node:
return monitored
left = deeper(node.left)
right = deeper(node.right)
# must install camera to monitored one (or both) children
if left == unknown or right == unknown:
nonlocal result
result += 1
return camera
# node is next to a camera
if left == camera or right == camera:
return monitored
# left == monitored and right == monitored
return unknown
# both children are monitored, but not root itself
if deeper(root) == unknown:
result += 1 # install camera
return result
Difficulty
and has an acceptance rate of about 48% (400k+ submissions).
Typical patterns to solve this problem:
- Binary Tree
- Depth First Search
- Dynamic Programming
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic binary-tree camera placement problem. It defines a depth-first traversal that classifies each subtree into three states:
- unknown - the subtree is not covered by any camera.
- monitored - the subtree is covered but does not contain a camera.
- camera - a camera is placed at the current node.
A global counter result records the total number of cameras required.
The algorithm walks the tree once, deciding locally whether a camera is needed based on the states returned by the children.
Core Logic
State Constants
unknown = -1
monitored = 0
camera = +1
These integer constants make the comparison logic concise and avoid string handling overhead.
Recursive Helper
def deeper(node):
if not node:
return monitored
left = deeper(node.left)
right = deeper(node.right)
...
The helper deeper returns the state of the subtree rooted at node.
A None node is considered already monitored, which eliminates the need for special-case checks later in the recursion.
Camera Placement Decision
if left == unknown or right == unknown:
nonlocal result
result += 1
return camera
If either child is uncovered (unknown), a camera must be installed at the current node.
The nonlocal declaration updates the outer result variable without using a mutable container.
Propagation of Coverage
if left == camera or right == camera:
return monitored
When at least one child already hosts a camera, the current node is automatically covered, so it returns monitored.
Uncovered Leaf Propagation
return unknown
If both children are covered (monitored) and none holds a camera, the current node remains uncovered, propagating the unknown state upward.
Final Root Check
if deeper(root) == unknown:
result += 1
After the full traversal, if the root itself is still uncovered, an additional camera is placed at the root.
Edge Cases Handled
When the input tree is empty (root is None), the initial call to deeper returns monitored, and the final check does not increment result. The function correctly returns 0 cameras for an empty tree.
For a single-node tree, the recursive call on the left and right children yields monitored. The node therefore returns unknown, triggering the final root check and resulting in exactly one camera, which is the optimal solution.
Leaf nodes are naturally handled: their children are None (treated as monitored), so the leaf itself returns unknown. Its parent then detects the unknown child and installs a camera, covering both the leaf and the parent.
Performance Optimizations
The algorithm performs a single post-order traversal, ensuring each node is visited exactly once. By using integer constants for state representation, the code avoids the overhead of object creation or string comparison. The early return pattern-installing a camera as soon as an uncovered child is detected-prevents unnecessary further computation in that branch. The use of a nonlocal integer for the camera count eliminates the need for a mutable list or dictionary, keeping the memory footprint minimal.
Overall, the solution achieves the desired result with linear time behavior relative to the number of nodes, while maintaining a low constant factor due to its compact state handling and in-place counter update.
ELI5 - Simplified Explanation
The code acts like a tiny security guard wandering through a tree-shaped house. To keep the whole house safe, cameras need to be placed in the rooms, but the goal is to use the smallest number of cameras possible. The code starts at the very top of the tree and looks down at all the rooms beneath it. When the code explores, it learns a few things about each room. A room might be empty and need a camera, a room might be already watched by a camera nearby, or a room might have a camera inside it.
The process happens by checking the rooms at the very bottom first. If any of those bottom rooms are not being watched, the code puts a camera in the room just above them. This is a smart choice because a camera placed there can look at the room it is in, plus the rooms above and below it. As the code moves back up toward the top, it keeps track of how many cameras are used by adding to a counting box. If it reaches the very top and notices that the first room is still not being watched, it adds one final camera to make sure everything is safe. Think of it like a game of hide and seek where the cameras are trying to find every single corner of the building.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1763: Longest Nice Substring
- problem 1653: Minimum Deletions to Make String Balanced
- problem 1749: Maximum Absolute Sum of Any Subarray
- problem 761: Special Binary String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality