Skip to problem
←

Binary Tree Cameras

Hard 0 attempts

You're given the root of a binary tree and need to place security cameras on some of its nodes so that every node in the tree is watched. A camera placed on a node covers that node, its parent, and its direct children. Return the fewest cameras needed to cover the entire tree.

Function contract

Implement minCameraCover(root). The runner converts the level-order input array into nodes with val, left, and right fields; [] becomes null.

Output: The minimum number of cameras needed to cover every node. A camera covers its own node, its parent, and its immediate children.

Example 1

Input
root = [0,0,null,0,0]
Output
1

Example 2

Input
root = [0]
Output
1
Visual Aid
One camera covers all four nodes
0000Peach node: camera location

The camera on the root’s left child watches all four nodes. Node values are labels, not camera indicators.

Constraints
  • 1 <= number of nodes <= 1000
  • Node.val == 0

Greedy DFS (Bottom-Up)

Each node has 3 states: 0 = needs camera, 1 = has camera, 2 = covered. Greedily place cameras at parents of uncovered leaves.

javascript
function minCameraCover(root) {
  let cameras = 0;
  function dfs(node) {
    if (!node) return 2;
    const l = dfs(node.left),
      r = dfs(node.right);
    if (l === 0 || r === 0) {
      cameras++;
      return 1;
    }
    if (l === 1 || r === 1) return 2;
    return 0;
  }
  if (dfs(root) === 0) cameras++;
  return cameras;
}

Time: O(n) | Space: O(h)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript