Count the Number of Good Nodes Problem
Description
LeetCode Problem 3249.
There is an undirected tree with n nodes labeled from 0 to n - 1, and rooted at node 0. You are given a 2D integer array edges of length n - 1, where edges[i] = [a_i, b_i] indicates that there is an edge between nodes a_i and b_i in the tree.
A node is good if all the subtrees rooted at its children have the same size.
Return the number of good nodes in the given tree.
A subtree of treeName is a tree consisting of a node in treeName and all of its descendants.
Example 1:
Input: edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
Output: 7
Explanation:

All of the nodes of the given tree are good.
Example 2:
Input: edges = [[0,1],[1,2],[2,3],[3,4],[0,5],[1,6],[2,7],[3,8]]
Output: 6
Explanation:

There are 6 good nodes in the given tree. They are colored in the image above.
Example 3:
Input: edges = [[0,1],[1,2],[1,3],[1,4],[0,5],[5,6],[6,7],[7,8],[0,9],[9,10],[9,12],[10,11]]
Output: 12
Explanation:

All nodes except node 9 are good.
Constraints:
2 <= n <= 10^5edges.length == n - 1edges[i].length == 20 <= a_i, b_i < n- The input is generated such that
edgesrepresents a valid tree.
Solution
Approach: DFS
Build an adjacency list and run a DFS from node 0, where dfs(a, parent) returns the size of the subtree rooted at a.
While visiting the children of a, remember the size of the first child subtree and compare every later child subtree with it. If any size differs, a is not good. Add the subtree sizes to get the size of a's own subtree, count a when it is good, and return the size to the caller. A leaf has no children, so it is always good.
Complexity: O(n) time and O(n) space.
from collections import defaultdict
class Solution:
def countGoodNodes(self, edges: List[List[int]]) -> int:
def dfs(a: int, fa: int) -> int:
pre = -1
cnt = ok = 1
for b in g[a]:
if b != fa:
cur = dfs(b, a)
cnt += cur
if pre < 0:
pre = cur
elif pre != cur:
ok = 0
nonlocal ans
ans += ok
return cnt
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
ans = 0
dfs(0, -1)
return ans