class Solution {
private:
vector<vector<int>> cnt;
void dfs(int tmp, int par, vector<vector<int>> &graph){
for(auto u: graph[tmp]){
if(par!=u){
dfs(u, tmp, graph);
for(int i=0; i<26; i++){
cnt[tmp][i] += cnt[u][i];
}
}
}
}
public:
vector<int> countSubTrees(int n, vector<vector<int>>& edges, string labels) {
vector<vector<int>> graph(n);
for(auto &e: edges){
graph[e[0]].push_back(e[1]);
graph[e[1]].push_back(e[0]);
}
cnt.resize(n, vector<int>(26,0));
for(int i=0; i<n; i++)
cnt[i][labels[i]-'a']++;
dfs(0,-1,graph);
vector<int> ans(n);
for(int i=0; i<graph.size(); i++){
for(int j=0; j<graph[i].size(); j++){
cout<<graph[i][j]<<" ";
}
cout<<endl;
}
for(int i=0; i<n; i++)
ans[i] = cnt[i][labels[i]-'a'];
return ans;
}
};
Leetcode 1519. Number of Nodes in the Sub-Tree With the Same Label DFS 图遍历
最新推荐文章于 2021-03-20 14:32:50 发布