Binary tree cameras solution explained

Binary Tree Cameras asks for the fewest cameras so that every node is watched, where a camera watches its own node, its parent and its children. The standard solution is a greedy postorder walk in which each node reports one of three states (needs watching, has a camera, already watched); a node puts a camera on itself only when a child needs watching. It runs in O(n) time and O(h) space, and a three-value dynamic program over the same walk proves the answer optimal.

By Published 8 min read

The problem in plain words

Every node of a binary tree must be watched. You may install a camera on any node; it watches that node, the node's parent and the node's children, nothing farther. Return the smallest number of cameras that watches every node. Node values are irrelevant. An empty tree needs none and a single node needs one.

        r
       /
     [b]          camera on b watches r, b, c and d
     / \
    c   d
         \
         [e]      camera on e watches d, e and f
           \
            f
Our example: 6 nodes, answer 2 (camera nodes shown in brackets)

One camera cannot do it: the best single spot, b, reaches four of the six nodes. Two are enough, on b and e. Notice that neither camera sits on a leaf.

Why interviewers like it

It is usually listed as a hard problem, yet it rewards a single good insight rather than heavy code. The interviewer wants to see you reason about where a camera is most useful, turn that into a rule, and implement it as a postorder walk where each node decides only from its children's reports. It is a compact test of tree DP thinking, and the follow-up, "prove the greedy is optimal", separates candidates who guessed from those who understood.

Brute force: try camera sets from smallest up

Collect every node with its neighbors (parent and children). For k = 0, 1, 2 and so on, try every set of k nodes and check whether together they watch everything. The first k that works is the answer. With n nodes there are 2^n sets, so this is only a test oracle for trees of a dozen nodes. It is still worth writing in practice, because it lets you check the clever solution against the definition.

from itertools import combinations


def cameras_brute(root):
    nodes, nbrs = [], {}

    def collect(node, parent):
        if node is None:
            return
        nodes.append(node)
        nbrs[node] = [n for n in (parent, node.left, node.right) if n]
        collect(node.left, node)
        collect(node.right, node)

    collect(root, None)
    for k in range(len(nodes) + 1):                 # try 0 cameras, then 1, then 2...
        for chosen in combinations(nodes, k):
            watched = set(chosen)
            for cam in chosen:
                watched.update(nbrs[cam])
            if len(watched) == len(nodes):
                return k
Python, exhaustive search over node sets. Exponential; a correctness reference only.

The insight: cameras belong on leaves' parents

A leaf must be watched, either by a camera on itself or on its parent. A camera on the parent watches the leaf too, plus the parent, its other child and the grandparent. So moving any leaf camera up to the parent never loses coverage and never adds cameras. Apply the same argument bottom up: once leaves are handled, treat the watched nodes as settled and repeat. Postorder is the natural order, because a node can only decide after hearing from both children.

Each node returns one of three states to its parent. NEEDS: this node is not watched yet. HAS_CAMERA: a camera sits here. COVERED: watched by a child's camera, no camera here. A missing child returns COVERED, so leaves never feel obliged to install anything for an empty child. The rules, in priority order: if either child NEEDS, install a camera here; otherwise, if either child HAS_CAMERA, this node is COVERED; otherwise it NEEDS its parent. At the very end, a root that still NEEDS gets one more camera, because it has no parent to rely on.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right


NEEDS, HAS_CAMERA, COVERED = 0, 1, 2


def min_cameras(root):
    count = 0

    def visit(node):
        nonlocal count
        if node is None:
            return COVERED                  # an empty child never needs watching
        left, right = visit(node.left), visit(node.right)
        if left == NEEDS or right == NEEDS:
            count += 1                      # a child is unwatched: only this node can fix it
            return HAS_CAMERA
        if left == HAS_CAMERA or right == HAS_CAMERA:
            return COVERED
        return NEEDS                        # leave it for the parent to cover

    if visit(root) == NEEDS:                # the root has no parent to rely on
        count += 1
    return count
Python, greedy postorder. O(n) time, O(h) recursion.
function minCameras(root) {
  const NEEDS = 0, HAS_CAMERA = 1, COVERED = 2;
  let count = 0;
  function visit(node) {
    if (!node) return COVERED;
    const left = visit(node.left);
    const right = visit(node.right);
    if (left === NEEDS || right === NEEDS) {
      count += 1;
      return HAS_CAMERA;
    }
    if (left === HAS_CAMERA || right === HAS_CAMERA) return COVERED;
    return NEEDS;
  }
  if (visit(root) === NEEDS) count += 1;
  return count;
}
JavaScript, the same three states.

On the example: f is a leaf with two empty children, so it reports NEEDS. e sees a needy child and installs a camera. d sees a camera below and reports COVERED. c, a leaf, reports NEEDS. b sees a needy child, so it installs the second camera. r sees a camera below and is COVERED. Two cameras.

Proving it with a dynamic program

If the interviewer asks why greedy is optimal, a DP gives the same answer without any exchange argument. For each subtree, compute three minimum costs, all of which require every node below to be watched: a camera on this node; no camera here but a child's camera watches it; or this node left unwatched for its parent to cover. Each is a small formula over the children's three values, and the answer is the smaller of the first two at the root.

INF = float("inf")


def min_cameras_dp(root):
    # For each subtree, three costs (every node below is watched in all three):
    #   here    = camera on this node
    #   watched = no camera here, but a child's camera watches this node
    #   open    = this node is not watched yet; the parent must have a camera
    def visit(node):
        if node is None:
            return INF, 0, 0
        lh, lw, lo = visit(node.left)
        rh, rw, ro = visit(node.right)
        here = 1 + min(lh, lw, lo) + min(rh, rw, ro)
        watched = min(lh + min(rh, rw), rh + min(lh, lw))
        open_ = lw + rw
        return here, watched, open_

    here, watched, _ = visit(root)
    return min(here, watched) if root else 0
Python, three-state DP. O(n) time; matches the greedy on every tested tree.

Complexity

n nodes, height h
ApproachTimeExtra space
Try all camera setsO(2^n · n)O(n)
Greedy postorder with three statesO(n)O(h) recursion
Three-value DPO(n)O(h) recursion
n nodes, height h. Scroll sideways on a small screen.

A quick sanity check for your code: on a chain of n nodes the answer is n divided by 3, rounded up, since each camera in the middle of a chain covers three consecutive nodes.

Edge cases to test

  • Empty tree (0) and a single node (1, added by the root check).
  • Two nodes: one camera, on either.
  • A root whose children both have cameras: the root is covered, no extra camera.
  • A root left NEEDS after the walk, such as a root whose only child is covered by a grandchild's camera.
  • Long chains, against the n / 3 rule; deep chains also test the recursion limit in Python.

Common mistakes

  • Treating a missing child as NEEDS, which puts cameras on every leaf.
  • Checking HAS_CAMERA before NEEDS. If one child has a camera and the other needs one, this node must still install a camera.
  • Forgetting the final root check.
  • Trying a top-down greedy from the root, which has no guarantee and fails on simple chains.
  • Counting cameras in a global variable that is not reset between test cases.

How to explain it out loud

Fictional example

Getting to the insight in front of the interviewer
Candidate
A leaf can be watched by a camera on itself or its parent. The parent covers everything the leaf camera would, and more, so I never put a camera on a leaf.
Candidate
That suggests working bottom up. Each node tells its parent one of three things: I need watching, I have a camera, or I am already covered.
Candidate
If any child needs watching, I install a camera here. If a child has a camera, I am covered. Otherwise I ask my parent. The root gets a camera if it is still uncovered at the end.
Interviewer
How do you know that is optimal?
Candidate
The exchange argument: moving a camera from a leaf to its parent never hurts. I can also back it with a three-state DP over the same postorder, which computes the true minimum.

This is a postorder computation at heart; Binary Tree Postorder Traversal covers the visiting order. Another tree problem that edits structure bottom up is Trim a Binary Search Tree, and Recover Binary Search Tree shows a different kind of reasoning over the same walk. The dynamic programming patterns guide puts tree DP next to the other families.

Practicing with Natively

Hard problems like this one are where a nudge in practice beats an hour of staring. Natively can read the problem from a screenshot on Mac or Windows and, if you ask, give only the hint about leaves before showing any code, then check your state rules against small trees. It also keeps a transcript of the mock, so you can review how clearly you argued optimality.

Questions people ask

How do you solve Binary Tree Cameras?

Walk the tree in postorder. Each node reports whether it needs watching, has a camera or is covered. Install a camera on a node when any child needs watching, and add one at the root if it is still unwatched.

Why is the greedy solution for Binary Tree Cameras optimal?

A camera on a leaf's parent watches everything a camera on the leaf would, and more, so leaf cameras can always be moved up. A three-state dynamic program over the same walk confirms the minimum.

What is the time complexity of Binary Tree Cameras?

O(n) time, since each node is visited once, and O(h) space for the recursion, where h is the tree's height.

How should a null child be treated in Binary Tree Cameras?

As already covered. Treating it as needing a camera forces cameras onto every leaf and overcounts.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP