Imagine you are installing security cameras in a large building represented as a binary tree. Each camera can monitor its parent, itself, and its immediate children. How do you place the minimum number of cameras to cover every room?
Given a binary tree, we need to place cameras on some nodes of the tree. 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.
The number of nodes in the tree is in the range [1, 10^5].Each node's value is unique (not necessarily required but typical).
Edge cases: Single node tree → 1 camera neededComplete binary tree with height 1 → 1 camera neededSkewed tree (all left or all right) → cameras placed at alternate nodes
def minCameraCover(root: Optional[TreeNode]) -> int:public int minCameraCover(TreeNode root)int minCameraCover(TreeNode* root)function minCameraCover(root)
def minCameraCover(root):
# Write your solution here
pass
class Solution {
public int minCameraCover(TreeNode root) {
// Write your solution here
return 0;
}
}
#include <vector>
using namespace std;
int minCameraCover(TreeNode* root) {
// Write your solution here
return 0;
}
function minCameraCover(root) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: Number of cameras equal to number of leavesGreedy approach placing cameras only at leaves without considering parents.✅ Implement postorder DFS with three states and place cameras at parents of uncovered nodes.
Wrong: 0 cameras for single node treeNot handling base case where single node must have a camera.✅ Add base case: if node is leaf and uncovered, place camera.
Wrong: More cameras than minimal in complete binary treeNot recognizing that one camera at root covers entire tree.✅ Use postorder DFS to check coverage and avoid redundant cameras.
Wrong: TLE on large inputUsing brute force exponential recursion instead of linear DFS.✅ Use O(n) postorder DFS with three states to achieve linear time complexity.
Wrong: Incorrect camera count due to off-by-one coverage errorMismanagement of coverage states leading to undercounting cameras.✅ Carefully update coverage states in postorder traversal to avoid off-by-one errors.