progress

~/problems / Trees / Tree DP

Binary tree cameras

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

hard ~40 min

You may install cameras on nodes of a binary tree. A camera watches its own node, its parent, and its direct children.

Write min_camera_cover(root: TreeNode) -> int: the fewest cameras so that every node is watched. TreeNode(val, left=None, right=None) is in the starter; node values don't matter.

Examples:

  • A single node needs 1 camera.
  • A root with one child, which has two children of its own, needs 1 (put it on the middle node).
  • A straight chain of 5 nodes needs 2 (on the 2nd and 5th, or on the 2nd and 4th).
Left: a root with one child that has two children, all watched by a single camera on the middle node. Right: a chain of five nodes watched by cameras on the second and fifth nodes

Constraints: 1 to about 130,000 nodes; the big test is a balanced tree. Trying sets of nodes is exponential.

⭐ Bonus: a speed test on the 130,000-node tree earns a star in O(n).

Show hint

Think bottom-up. Is a camera on a leaf ever better than one on the leaf's parent? From there, what does each node need to know about its children to decide whether it must hold a camera?

Topic: Tree DP. Post-order: each node returns a small tuple of states to its parent.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc