Approach
Depth-first search
For Count the Number of Good Nodes, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 49 lines of C++ from the credited upstream file 3249.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int countGoodNodes(vector<vector<int>>& edges) {4 const int n = edges.size() + 1;5 int ans = 0;6 vector<vector<int>> graph(n);7 8 for (const vector<int>& edge : edges) {9 const int u = edge[0];10 const int v = edge[1];11 graph[u].push_back(v);12 graph[v].push_back(u);13 }14 15 dfs(graph, 0, -1, ans);16 return ans;17 }18 19 private:20 int ans = 0;21 22 23 int dfs(const vector<vector<int>>& graph, int u, int prev, int& ans) {24 int size = 1;25 vector<int> childrenSizes;26 27 for (const int v : graph[u]) {28 if (v == prev)29 continue;30 const int childSize = dfs(graph, v, u, ans);31 size += childSize;32 childrenSizes.push_back(childSize);33 }34 35 if (childrenSizes.empty() || allSameSizes(childrenSizes))36 ++ans;37 38 return size;39 }40 41 private:42 bool allSameSizes(const vector<int>& childrenSizes) {43 for (int i = 1; i < childrenSizes.size(); ++i)44 if (childrenSizes[i] != childrenSizes[0])45 return false;46 return true;47 }48};49