Number of Nodes in the Sub-Tree With the Same Label LeetCode solution in JavaScript

1
var countSubTrees = function (n, edges, labels) {
2
const adj = [];
3

4
for (let i = 0; i < n; i++) {
5
adj[i] = [];
6
}
7

8
for (const [u, v] of edges) {
9
adj[u].push(v);
10
adj[v].push(u);
11
}
12

13
const resCount = new Array(n).fill(0);
14

15
dfs(0, -1);
16

17
return resCount;
18

19
function dfs(node, parent) {
20
const label = labels.charCodeAt(node) - 97;
21

22
const charCount = new Array(26).fill(0);
23

24
charCount[label] = 1;
25

26
for (const childNode of adj[node]) {
27
if (childNode == parent) continue;
28

29
const subCount = dfs(childNode, node);
30

31
for (let i = 0; i < 26; i++) {
32
charCount[i] += subCount[i];
33
}
34
}
35

36
resCount[node] = charCount[label];
37
return charCount;
38
}
39
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0