Skip to content
BytePatterns

Fewest Watchers on a Tree

HardDynamic Programming#tree-dp#state-machine~45m

Problem

A watcher placed on a node of a binary tree keeps an eye on that node, its parent and its children. Return the fewest watchers needed so that every node in the tree is watched. An empty tree needs none.

Examples

Input:  tree = 1, left 2, whose children are 3 and 4
Output: 1
Why:    a watcher on 2 covers 1, 3 and 4 as well as itself
Input:  tree = a chain of five nodes, each the left child of the one before
Output: 2
Why:    watchers on the second and fourth nodes cover all five
Input:  tree = a single node
Output: 1
Why:    edge case, the root has to watch itself

Hints

0 / 3

Stuck on the idea rather than the code? DP on Trees covers it.