Binary Tree Cameras

Hard Trees & BST Postorder + Multiple Return Values

Binary Tree Cameras is a hard trees & bst problem solved with the postorder + multiple return values pattern. The best approach, greedy postorder, runs in O(n) time and O(h) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from tree dp with three states up.

Problem

You are given the root of a binary tree. You may install cameras on its nodes. A camera on a node watches that node, its parent, and its immediate children.

Return the minimum number of cameras needed so that every node of the tree is watched by at least one camera.

Examples

Example 1

Input
root = [0, 0, null, 0, 0]
Output
1
Why
One camera on the root's left child watches the root above it and both of its own children below it.

Example 2

Input
root = [0, 0, 0, 0, null, null, 0]
Output
2
Why
The root has two children, and each of them has one leaf below it. A camera on each child covers everything: each watches its leaf, itself and the root. One camera cannot reach both leaves.

Example 3

Input
root = [0]
Output
1
Why
A lone node can only be watched by a camera on itself.

Constraints

  • The tree has 1 to 1000 nodes.
  • Node.val == 0

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Tree DP with three statesO(n)O(h)
Greedy postorderO(n)O(h)

1Tree DP with three states

TimeO(n)Each node is visited once and does a constant amount of work with its children's three numbers.
SpaceO(h)The recursion stack is as deep as the tree; each call keeps only three numbers.

For every node compute three costs for its subtree, all counting the fewest cameras so that every node below it is watched: (0) the node holds a camera; (1) the node has no camera but a child's camera watches it; (2) the node has no camera and is not watched yet, so its parent must hold one. Combine the children's three numbers in a postorder pass. A null child costs nothing as watched and can never hold a camera.

  1. null → {INF, 0, 0}: no camera can sit there, and it needs no watching.
  2. With a camera: 1 + min of the left child's three states + min of the right child's three states (any child is fine, the camera watches it).
  3. Watched by a child: one child holds a camera and the other is either a camera or already watched: min(L0 + min(R0, R1), R0 + min(L0, L1)).
  4. Not watched: both children must be watched without help from this node: L1 + R1.
  5. The root has no parent, so the answer is min(state 0, state 1) at the root.
class Solution {
    private static final int INF = 1_000_000;

    public int minCameraCover(TreeNode root) {
        int[] r = solve(root);
        return Math.min(r[0], r[1]);
    }

    // {camera here, watched by a child, not watched yet}
    private int[] solve(TreeNode node) {
        if (node == null) return new int[] { INF, 0, 0 };
        int[] L = solve(node.left), R = solve(node.right);
        int camera = 1 + min3(L) + min3(R);
        int watched = Math.min(L[0] + Math.min(R[0], R[1]), R[0] + Math.min(L[0], L[1]));
        int unwatched = L[1] + R[1];
        return new int[] { camera, Math.min(watched, INF), Math.min(unwatched, INF) };
    }

    private int min3(int[] a) {
        return Math.min(a[0], Math.min(a[1], a[2]));
    }
}

2Greedy postorder

TimeO(n)One postorder visit per node with constant work.
SpaceO(h)Only the recursion stack, as deep as the tree.

Leaves should never hold cameras; their parents should. Go bottom up and let each node report one of three states to its parent: 0 = not watched, 1 = watched without a camera, 2 = holds a camera. A node with an unwatched child must take a camera. A node with a camera child is watched. Otherwise it stays unwatched and its parent will take a camera, which is as high as a camera can go while still covering it. A missing child reports 1, so it never forces anything.

  1. dfs(null) = 1 (watched, it needs nothing).
  2. Get left and right from the children first (postorder).
  3. If either is 0: place a camera here (cameras++) and return 2.
  4. Else if either is 2: return 1, this node is watched.
  5. Else return 0: this node waits for its parent.
  6. After the pass, if the root reported 0, it has no parent to rely on: add one more camera.
class Solution {
    private int cameras;

    public int minCameraCover(TreeNode root) {
        cameras = 0;
        if (dfs(root) == 0) cameras++;
        return cameras;
    }

    // 0 = not watched, 1 = watched, 2 = has a camera
    private int dfs(TreeNode node) {
        if (node == null) return 1;
        int left = dfs(node.left);
        int right = dfs(node.right);
        if (left == 0 || right == 0) {
            cameras++;
            return 2;
        }
        if (left == 2 || right == 2) return 1;
        return 0;
    }
}

Edge cases to test

  • A single node (answer 1)
  • A chain (every node has one child): one camera for every three nodes, rounded up
  • A root left uncovered after the postorder pass needs its own camera
  • A perfect tree, where putting cameras on the leaves is wasteful
  • Deep trees (a chain of 1000 nodes) for the recursion depth

Hints

Hint 1

Never put a camera on a leaf: its parent watches the leaf and everything the leaf would have watched, and more.

Hint 2

Work from the bottom up. For each node, ask what its children report: is a child unwatched, watched, or holding a camera?

Hint 3

If any child is unwatched, this node must hold a camera. If a child holds a camera, this node is watched for free. Otherwise leave it unwatched and let its parent deal with it.

FAQ

What is the best time complexity for Binary Tree Cameras?

Greedy postorder runs in O(n) time and O(h) extra space. One postorder visit per node with constant work.

Which pattern does Binary Tree Cameras use?

It is a trees & bst problem that uses the postorder + multiple return values pattern. Other problems with the same pattern: Balanced Binary Tree, Validate Binary Search Tree, Children Sum in a Binary Tree.

Is there a brute force solution for Binary Tree Cameras?

Yes. Tree DP with three states takes O(n) time and O(h) space. For every node compute three costs for its subtree, all counting the fewest cameras so that every node below it is watched: (0) the node holds a camera; (1) the node has no camera but a child's camera watches it; (2) the node has no camera and is not watched yet, so its parent must hold one.

Which edge cases should I test for Binary Tree Cameras?

A single node (answer 1); A chain (every node has one child): one camera for every three nodes, rounded up; A root left uncovered after the postorder pass needs its own camera; A perfect tree, where putting cameras on the leaves is wasteful; Deep trees (a chain of 1000 nodes) for the recursion depth.