|
| 1 | +/** |
| 2 | + * 1519. Number of Nodes in the Sub-Tree With the Same Label |
| 3 | + * https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a tree (i.e. a connected, undirected graph that has no cycles) |
| 7 | + * consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The |
| 8 | + * root of the tree is the node 0, and each node of the tree has a label which |
| 9 | + * is a lower-case character given in the string labels (i.e. The node with the |
| 10 | + * number i has the label labels[i]). |
| 11 | + * |
| 12 | + * The edges array is given on the form edges[i] = [ai, bi], which means there |
| 13 | + * is an edge between nodes ai and bi in the tree. |
| 14 | + * |
| 15 | + * Return an array of size n where ans[i] is the number of nodes in the subtree |
| 16 | + * of the ith node which have the same label as node i. |
| 17 | + * |
| 18 | + * A subtree of a tree T is the tree consisting of a node in T and all of its |
| 19 | + * descendant nodes. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} n |
| 24 | + * @param {number[][]} edges |
| 25 | + * @param {string} labels |
| 26 | + * @return {number[]} |
| 27 | + */ |
| 28 | +var countSubTrees = function(n, edges, labels) { |
| 29 | + const lookup = Array.from(Array(n), () => []); |
| 30 | + const result = new Array(n).fill(0); |
| 31 | + |
| 32 | + edges.forEach(([x, y]) => { |
| 33 | + lookup[x].push(y); |
| 34 | + lookup[y].push(x); |
| 35 | + }); |
| 36 | + |
| 37 | + function bfs(index, previous, chars = new Array(26).fill(0)) { |
| 38 | + const key = labels.charCodeAt(index) - 97; |
| 39 | + const count = chars[key]; |
| 40 | + chars[key]++; |
| 41 | + lookup[index].forEach(i => { |
| 42 | + if (i !== previous) { |
| 43 | + bfs(i, index, chars); |
| 44 | + } |
| 45 | + }); |
| 46 | + result[index] = chars[key] - count; |
| 47 | + } |
| 48 | + |
| 49 | + bfs(0, -1); |
| 50 | + |
| 51 | + return result; |
| 52 | +}; |
0 commit comments