Skip to content

Commit 05620ce

Browse files
Create number-of-nodes-in-the-sub-tree-with-the-same-label.cpp
1 parent 95262ed commit 05620ce

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
vector<int> fun(vector<vector<int>> &adj, string &labels, int i,vector<int>&result){
4+
vector<int> ans(26, 0);
5+
result[i] = 1;
6+
ans[labels[i] - 'a'] = 1;
7+
8+
for(int j = 0; j != adj[i].size(); j++)
9+
if(!result[adj[i][j]]){
10+
vector<int> tmp = fun(adj, labels,adj[i][j],result);
11+
for(int k = 0; k != 26; k++) ans[k] += tmp[k];
12+
}
13+
14+
result[i] = ans[labels[i] - 'a'];
15+
16+
return ans;
17+
}
18+
19+
vector<int> countSubTrees(int n, vector<vector<int>>& edges, string labels) {
20+
vector<vector<int>> adj(n);
21+
vector<int> result(n,0);
22+
for(int i = 0; i != edges.size(); i++)
23+
{adj[edges[i][0]].push_back(edges[i][1]);
24+
adj[edges[i][1]].push_back(edges[i][0]);
25+
}
26+
27+
fun(adj, labels, 0,result);
28+
return result;
29+
}
30+
};

0 commit comments

Comments
 (0)