Problem
Alice has an undirected tree with n
nodes labeled from 0
to n - 1
. The tree is represented as a 2D integer array edges
of length n - 1
where
edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and
bi
in the tree.
Alice wants Bob to find the root of the tree. She allows Bob to make several guesses about her tree. In one guess, he does the following:
- Chooses two distinct integers
u
andv
such that there exists an edge[u, v]
in the tree. - He tells Alice that
u
is the parent ofv
in the tree.
Bob’s guesses are represented by a 2D integer array guesses
where
guesses[j] = [uj, vj]
indicates Bob guessed uj
to be the parent of vj
.
Alice being lazy, does not reply to each of Bob’s guesses, but just says that
at least k
of his guesses are true
.
Given the 2D integer arrays edges
, guesses
and the integer k
, return thenumber of possible nodes that can be the root of Alice’s tree. If there is no such tree, return 0
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
edges.length == n - 1
2 <= n <= 10^5
1 <= guesses.length <= 10^5
0 <= ai, bi, uj, vj <= n - 1
ai != bi
uj != vj
edges
represents a valid tree.guesses[j]
is an edge of the tree.guesses
is unique.0 <= k <= guesses.length
Solution
Method 1 – Rerooting DFS with Guess Counting
Intuition
We want to count how many nodes can be the root such that at least k guesses are correct. We can use DFS to count the number of correct guesses for one root, then reroot the tree and update the count efficiently for all possible roots.
Approach
- Build the tree as an adjacency list.
- Store all guesses in a set for O(1) lookup.
- Use DFS to count the number of correct guesses if node 0 is the root.
- Use rerooting DFS: for each child, update the count based on whether the guess (parent, child) is in the set, and recursively check all possible roots.
- Count the number of roots where the number of correct guesses is at least k.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + m)
, where n is the number of nodes and m is the number of guesses, since we visit each node and guess once. - 🧺 Space complexity:
O(n + m)
, for storing the tree and guesses.