Problem 614
Binary Tree Cameras
Hard · 30 pts · Tree, Greedy, Dynamic Programming
Problem
You may install cameras on the nodes of a binary tree. A camera monitors its own node, its parent and its immediate children. Find the minimum number of cameras needed so that every node is monitored. Greedy from the bottom works: a post-order search gives each node a state (needs cover, has a camera, or covered); a node gets a camera exactly when one of its children needs cover, and the root gets one if it is still uncovered at the end.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.
Output
Print the minimum number of cameras.
Constraints
1 <= number of nodes <= 1000; every value is 0
Example input
5 0 0 null 0 0
Example output
1
Explanation
In the tree 0 0 null 0 0, one camera on the root's left child monitors the root, itself and both of its children. All four nodes are covered, so the answer is 1.