DSA Factory
Free Timed practice lessonsTimed practice · Stage 0 · Timed set 1 · Step 4

Watching every branch

Place the fewest cameras in a tree so that every node is watched, where a camera watches its parent, itself and its children, using three states per node. About 22 minutes.

Three states

A camera at a node watches that node, its parent and its children. Work from the leaves up. Each subtree reports one of three states about its top node: zero if the node is not watched, one if it holds a camera, and two if it is watched by a camera below.

An empty child counts as watched, state two, so that it asks for nothing.

State 0: not watched yet.
State 1: has a camera.
In code
NOT_COVERED, COVERED, HAS_CAMERA = 0, 1, 2
Cameras for the tree 0, 0, 0, 0, none, none, 0, 0.
000000
cameras
0

The two leaves are not watched: state 0 each.

Move 1 of 5

Camera on the parent

If either child is not watched, this node must hold a camera, because only a camera here or on the child could watch it, and a camera on the parent also watches the grandparent. Add a camera and report state one.

Otherwise, if either child holds a camera, this node is watched: report state two. If neither applies, this node is not watched: report state zero and let the parent deal with it. At the root, state zero needs one more camera.

A child not watched: put a camera here.
Root not watched: add one more camera.
In code
if state == NOT_COVERED:
    cameras += 1
Quick check

Why not put cameras on the leaves?

  1. AA camera on the leaf's parent watches the leaf and also the grandparent and siblings
  2. BCameras do not work on leaves
  3. CLeaves are cheaper to cover
Show the answer

A camera on the leaf's parent watches the leaf and also the grandparent and siblings. It covers at least as much as a camera on the leaf would.

Your problem

Binary tree cameras

You install cameras on the nodes of a binary tree. A camera at a node monitors that node, its parent and its children. Given the root of a binary tree, return the minimum number of cameras needed to monitor every node.

Example
root = [0, 0, null, 0, 0] → 1

1 ≤ number of nodes ≤ 1,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve