Independent Set
Given an undirected tree with N vertices labeled from 1 to N. The graph is represented as a list of edges where edges[i] = [u, v] indicates an undirected edge between node u and node v.
Each vertex must be colored either: White or Black
Constraint: No two adjacent vertices can both be black
Your Task is to Count the number of valid colorings of the tree.
Return the answer: mod 109 + 7
Example 1:
Input: N = 3 ,edges = [[1,2], [2,3]]
Output: 5
Explanation:
Possible colorings:
WWW WWB WBW BWW BWB
Invalid:
BBW WBB BBB
Total = 5
Example 2:
Input: N = 4, edges = [[1,2], [1,3], [1,4]]
Output: 9
Explanation:
Tree:
1 / | \ 2 3 4
If node 1 is: Black thus children must be White => 1 way
If node 1 is: White children independently black/white => 2 choices each → 23 = 8
Total: 1 + 8 = 9
Now Your Turn!
Pick the correct output for the given inputInput: N = 5, edges = [[1,2], [1,3], [3,4], [3,5]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 ≤ N ≤ 105
- Edges = N-1
- Graph is a tree