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.
Example 1:
Input: root = [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.
Example 2:
Input: root = [0,0,null,0,null,0,null,null,0]
Output: 2
Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
Constraints:
The number of nodes in the tree is in the range [1, 1000].
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming · Tree
Example 1
[0,0,null,0,0]
Example 2
[0,0,null,0,null,0,null,null,0]
Related Problems
Distribute Coins in Binary Tree (distribute-coins-in-binary-tree)
Choose Edges to Maximize Score in a Tree (choose-edges-to-maximize-score-in-a-tree)
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #968: Binary Tree Cameras
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minCameraCover(TreeNode root) {
int[] ans = dfs(root);
return Math.min(ans[0], ans[1]);
}
private int[] dfs(TreeNode root) {
if (root == null) {
return new int[] {1 << 29, 0, 0};
}
var l = dfs(root.left);
var r = dfs(root.right);
int a = 1 + Math.min(Math.min(l[0], l[1]), l[2]) + Math.min(Math.min(r[0], r[1]), r[2]);
int b = Math.min(Math.min(l[0] + r[1], l[1] + r[0]), l[0] + r[0]);
int c = l[1] + r[1];
return new int[] {a, b, c};
}
}
// Accepted solution for LeetCode #968: Binary Tree Cameras
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minCameraCover(root *TreeNode) int {
var dfs func(*TreeNode) (int, int, int)
dfs = func(root *TreeNode) (int, int, int) {
if root == nil {
return 1 << 29, 0, 0
}
la, lb, lc := dfs(root.Left)
ra, rb, rc := dfs(root.Right)
a := 1 + min(la, min(lb, lc)) + min(ra, min(rb, rc))
b := min(la+ra, min(la+rb, lb+ra))
c := lb + rb
return a, b, c
}
a, b, _ := dfs(root)
return min(a, b)
}
# Accepted solution for LeetCode #968: Binary Tree Cameras
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minCameraCover(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if root is None:
return inf, 0, 0
la, lb, lc = dfs(root.left)
ra, rb, rc = dfs(root.right)
a = min(la, lb, lc) + min(ra, rb, rc) + 1
b = min(la + rb, lb + ra, la + ra)
c = lb + rb
return a, b, c
a, b, _ = dfs(root)
return min(a, b)
// Accepted solution for LeetCode #968: Binary Tree Cameras
/**
* [0968] Binary Tree Cameras
*
* 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.
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_01.png" style="width: 138px; height: 163px;" />
* Input: root = [0,0,null,0,0]
* Output: 1
* Explanation: One camera is enough to monitor all nodes if placed as shown.
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2018/12/29/bst_cameras_02.png" style="width: 139px; height: 312px;" />
* Input: root = [0,0,null,0,null,0,null,null,0]
* Output: 2
* Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
*
*
* Constraints:
*
* The number of nodes in the tree is in the range [1, 1000].
* Node.val == 0
*
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
// problem: https://leetcode.com/problems/binary-tree-cameras/
// discuss: https://leetcode.com/problems/binary-tree-cameras/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::rc::Rc;
enum Status {
Camera,
Covered,
NotCovered,
}
impl Solution {
pub fn min_camera_cover(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut camera_count = 0;
if let Status::NotCovered = Self::dfs_helper(&root, &mut camera_count) {
camera_count += 1;
}
camera_count
}
fn dfs_helper(node: &Option<Rc<RefCell<TreeNode>>>, camera_count: &mut i32) -> Status {
match node {
None => Status::Covered,
Some(node) => {
let node = node.borrow();
let left_status = Self::dfs_helper(&node.left, camera_count);
let right_status = Self::dfs_helper(&node.right, camera_count);
match (left_status, right_status) {
(Status::Covered, Status::Covered) => Status::NotCovered,
(Status::Camera, Status::Camera)
| (Status::Camera, Status::Covered)
| (Status::Covered, Status::Camera) => Status::Covered,
(Status::NotCovered, _) | (_, Status::NotCovered) => {
*camera_count += 1;
Status::Camera
}
}
}
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0968_example_1() {
let root = tree![0, 0, null, 0, 0];
let result = 1;
assert_eq!(Solution::min_camera_cover(root), result);
}
#[test]
fn test_0968_example_2() {
let root = tree![0, 0, null, 0, null, 0, null, null, 0];
let result = 2;
assert_eq!(Solution::min_camera_cover(root), result);
}
}
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(n)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.