Skip to content

Commit 9e24209

Browse files
committedJan 17, 2023
Add solution #1519
1 parent 5212370 commit 9e24209

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,7 @@
285285
1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy|
286286
1507|[Reformat Date](./1507-reformat-date.js)|Easy|
287287
1512|[Number of Good Pairs](./1512-number-of-good-pairs.js)|Easy|
288+
1519|[Number of Nodes in the Sub-Tree With the Same Label](./1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js)|Medium|
288289
1528|[Shuffle String](./1528-shuffle-string.js)|Easy|
289290
1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy|
290291
1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium|
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)
Please sign in to comment.