Binary Tree Cameras

HardTreestree dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the root of a binary tree. A camera can be installed on any node, and a camera watches the node it sits on, that node's parent, and that node's immediate children. Return the **minimum number of cameras** needed so that every node in the tree is watched. Node values are irrelevant (all are 0) and only the tree's shape matters. An O(n) post-order solution exists. It is either a small DP with three states per node or a greedy rule that places cameras as high above the leaves as possible.

Examples

Input: root = [0,0,null,0,0]
Output: 1
One camera on the root's left child watches all four nodes.
Input: root = [0,0,null,0,null,0,null,null,0]
Output: 2
The chain of five nodes needs two cameras, for example on the 2nd and 4th nodes.
Input: root = [0]
Output: 1
A lone node must host its own camera.

Constraints

  • 1 <= number of nodes <= 1000
  • Node.val == 0
  • Only the shape of the tree matters

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More tree dp problems