[LeetCode] Count the Number of Good Nodes

3249. Count the Number of Good Nodes

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] = [ai, bi] indicates that there is an edge between nodes ai and bi 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
int dfs(vector<vector<int>>& adj, int u, int par, int& res) {
unordered_set<int> us;
int sum = 1;
for(auto& v : adj[u]) {
if(v == par) continue;
int sub = dfs(adj,v,u,res);
us.insert(sub);
sum += sub;
}
res += (us.size() <= 1);
return sum;
}
public:
int countGoodNodes(vector<vector<int>>& edges) {
vector<vector<int>> adj(edges.size() + 1);
for(auto& e : edges) {
int u = e[0], v = e[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
int res = 0;
dfs(adj,0,-1,res);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/08/11/PS/LeetCode/count-the-number-of-good-nodes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.