Find the fewest cameras that monitor every node of a binary tree
Company: eBay
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Other
Overview: Find the minimum number of cameras needed to monitor every node of a binary tree, where a camera watches its own node, its parent and its children. It tests tree traversal, greedy decisions with a proof that they are optimal, and careful handling of leaves and the root.
Constraints
- The number of nodes is in the range [1, 1000].
- Node.val == 0 for every node.
- root is a level-order list: None marks a missing child, children of a missing node are not listed, and trailing None entries may be omitted.
Examples
Input: ([0],)
Expected Output: 1
Explanation: Source example: a single node has no neighbor to hold a camera, so it needs its own.
Input: ([0, 0],)
Expected Output: 1
Explanation: Root with one left leaf: one camera on either node covers both.
Hints
- A camera on a leaf monitors only the leaf and its parent. Compare that with what a camera on the leaf's parent would monitor.
- Try settling a node only after everything below it is settled. What does a node need to know about each of its children?
- The root has no parent, so nothing above it can monitor it.