classSolution { public: vector<int> smallestMissingValueSubtree(vector<int>& parents, vector<int>& nums){ int n = parents.size(); vector<vector<int>> G(n); for (int i = 1; i < n; i++) { G[parents[i]].push_back(i); } vector<int> sz(n), big_son(n, -1), ans(n); std::function<void(int, int)> get = [&](int u, int fa) { for (int v : G[u]) { if (v == fa) continue; get(v, u); sz[u] += sz[v]; if (big_son[u] == -1 || sz[v] > sz[big_son[u]]) { big_son[u] = v; } } }; get(0, -1); vector<int> bucket(n + 1, 0), pending; int cur = 0; std::function<void(int, int)> add = [&](int u, int fa) { if (nums[u] - 1 < n) { bucket[nums[u] - 1]++; pending.push_back(nums[u]); } for (int v : G[u]) { if (v == fa) continue; add(v, u); } }; std::function<void(int, int, bool)> dfs = [&](int u, int fa, bool del) { for (int v : G[u]) { if (v == fa) continue; if (v == big_son[u]) continue; dfs(v, u, true); } if (big_son[u] != -1) { dfs(big_son[u], u, false); } for (int v : G[u]) { if (v == fa) continue; if (v == big_son[u]) continue; add(v, u); } if (nums[u] - 1 < n) { bucket[nums[u] - 1]++; pending.push_back(nums[u]); } while (bucket[cur]) ++cur; ans[u] = cur + 1; if (del) { for (int num : pending) bucket[num - 1]--; pending.clear(); cur = 0; } }; dfs(0, -1, false); return ans; } };