Problem - Possible Root Nodes

LC 2581 - count valid root nodes

Assume that you have a tree and a list of guesses. Each guess says node aa is the parent of node bb if the tree is rooted at some node. Count how many root choices make at least kk guesses correct.

This is LeetCode 25812581, rated Hard.

The naive approach checks each of the nn possible roots separately. Too slow. You need to efficiently compute the answer for all nn roots. This is where rerooting DP comes in, and I'll walk you through it.