Approach
Depth-first search
For Find Subtree Sizes After Changes, 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
- 38 lines of C++ from the credited upstream file 3331.cpp.
- The implementation visibly relies on sequence storage.
- 4 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 vector<int> findSubtreeSizes(vector<int>& parent, string s) {4 const int n = parent.size();5 vector<int> ans(n);6 vector<int> newParent = parent;7 vector<vector<int>> tree(n);8 9 for (int i = 1; i < n; ++i) {10 const int closest = findClosestAncestor(i, parent, s);11 if (closest != -1)12 newParent[i] = closest;13 }14 15 for (int i = 1; i < n; ++i)16 tree[newParent[i]].push_back(i);17 18 dfs(tree, 0, ans);19 return ans;20 }21 22 private:23 24 int findClosestAncestor(int u, const vector<int>& parent, const string& s) {25 for (int curr = parent[u]; curr != -1; curr = parent[curr])26 if (s[curr] == s[u])27 return curr;28 return -1;29 }30 31 int dfs(const vector<vector<int>>& tree, int u, vector<int>& ans) {32 int sz = 1;33 for (const int v : tree[u])34 sz += dfs(tree, v, ans);35 return ans[u] = sz;36 }37};38