You are given an undirected tree and a set of "guesses" where each guess is a directed edge meaning is a parent of in the rooted tree. A node is a "possible root" if, when the tree is rooted at that node, at least guesses are correct. You need to count how many such possible root nodes exist.
Google uses this "Hard" problem to test a candidate's mastery of the Re-rooting technique in Dynamic Programming on Trees. It requires you to calculate a property for one root and then efficiently update that property as you "move" the root to adjacent nodes. This avoids the trap of running a full DFS for every possible root.
The pattern is DFS with Re-rooting (also known as the "Rerooting DP" pattern).
Tree: 0-1, Guesses: (0, 1), (1, 0), .
The biggest mistake is attempting to root the tree at every node and run a full DFS each time, resulting in which is too slow. Another error is not correctly identifying how a guess "flips" when the parent-child relationship is reversed. Using a set for guesses is also crucial for performance.
Study the "Re-rooting DP" pattern. It is the gold standard for tree problems where you need to calculate a global property for every single node. The key is always to identify what information is lost and what is gained when an edge is "flipped."
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Difference Between Maximum and Minimum Price Sum | Hard | Solve | |
| Minimum Increments to Equalize Leaf Paths | Medium | Solve | |
| Maximum Subtree of the Same Color | Medium | Solve | |
| Longest Special Path II | Hard | Solve | |
| Sum of Good Subsequences | Hard | Solve |