Number of Nodes in the Sub-Tree With the Same Label LeetCode solution in JavaScript
1var countSubTrees = function (n, edges, labels) {2const adj = [];34for (let i = 0; i < n; i++) {5adj[i] = [];6}78for (const [u, v] of edges) {9adj[u].push(v);10adj[v].push(u);11}1213const resCount = new Array(n).fill(0);1415dfs(0, -1);1617return resCount;1819function dfs(node, parent) {20const label = labels.charCodeAt(node) - 97;2122const charCount = new Array(26).fill(0);2324charCount[label] = 1;2526for (const childNode of adj[node]) {27if (childNode == parent) continue;2829const subCount = dfs(childNode, node);3031for (let i = 0; i < 26; i++) {32charCount[i] += subCount[i];33}34}3536resCount[node] = charCount[label];37return charCount;38}39};