Input: edges =[[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]Output: 7Explanation:

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

There are 6 good nodes in the given tree. They are colored in the image above.
A node is good if all its children have subtrees of the same size. We can use DFS to compute the size of each subtree and check for each node if all its children have the same subtree size.
classSolution {
publicintcountGoodNodes(int n, int[][] edges) {
List<Integer>[] g =new List[n];
for (int i = 0; i < n; ++i) g[i]=new ArrayList<>();
for (int[] e : edges) {
g[e[0]].add(e[1]);
g[e[1]].add(e[0]);
}
int[] sz =newint[n];
int[] ans =newint[1];
dfs(0, -1, g, sz, ans);
return ans[0];
}
voiddfs(int u, int p, List<Integer>[] g, int[] sz, int[] ans) {
sz[u]= 1;
List<Integer> childSizes =new ArrayList<>();
for (int v : g[u]) if (v != p) {
dfs(v, u, g, sz, ans);
sz[u]+= sz[v];
childSizes.add(sz[v]);
}
boolean good =true;
for (int i = 1; i < childSizes.size(); i++) {
if (!childSizes.get(i).equals(childSizes.get(0))) {
good =false;
break;
}
}
if (childSizes.isEmpty() || good) ans[0]++;
}
}
classSolution {
funcountGoodNodes(n: Int, edges: Array<IntArray>): Int {
val g = Array(n) { mutableListOf<Int>() }
for (e in edges) {
g[e[0]].add(e[1])
g[e[1]].add(e[0])
}
val sz = IntArray(n)
var ans = 0fundfs(u: Int, p: Int) {
sz[u] = 1val childSizes = mutableListOf<Int>()
for (v in g[u]) if (v != p) {
dfs(v, u)
sz[u] += sz[v]
childSizes.add(sz[v])
}
if (childSizes.isEmpty() || childSizes.all { it== childSizes[0] }) ans++ }
dfs(0, -1)
return ans
}
}
classSolution:
defcountGoodNodes(self, n: int, edges: list[list[int]]) -> int:
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
sz = [0] * n
ans =0defdfs(u: int, p: int) ->None:
nonlocal ans
sz[u] =1 child_sizes = []
for v in g[u]:
if v != p:
dfs(v, u)
sz[u] += sz[v]
child_sizes.append(sz[v])
ifnot child_sizes or all(x == child_sizes[0] for x in child_sizes):
ans +=1 dfs(0, -1)
return ans