#441 · Trees · Expert · 220 XP · about 40 min
You want to watch every node of a binary tree with security cameras. A camera placed on a node watches that node, its parent and its children. Write min_cameras(root) that returns the smallest number of cameras that together watch every node. An empty tree needs no cameras.
Each node is a Node with a value val and two children, left and right, which are None when missing. The provided build makes a tree from a list of values in level order, where None marks a missing child.
0 / 0 / \ 0 0
min_cameras(build([0, 0, None, 0, 0])) # returns 1 min_cameras(build([0, 0, None, 0, None, 0, None, None, 0])) # returns 2 min_cameras(build([0])) # returns 1
The drawing shows the first tree: one camera on the middle node watches all four nodes. The second tree is a chain of five nodes, which needs two cameras, for example on the second and the fourth node.
First solves only, ranked by stars and then time.