Skip to content

Commit 9137782

Browse files
authored
feat: add solutions to lc problem: No.1519 (doocs#904)
No.1519.Number of Nodes in the Sub-Tree With the Same Label
1 parent e6f0add commit 9137782

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

solution/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,33 @@ func countSubTrees(n int, edges [][]int, labels string) []int {
204204
}
205205
```
206206

207+
### **TypeScript**
208+
209+
```ts
210+
function countSubTrees(n: number, edges: number[][], labels: string): number[] {
211+
const dfs = (i: number, fa: number) => {
212+
const k = labels.charCodeAt(i) - 97;
213+
ans[i] -= cnt[k];
214+
cnt[k]++;
215+
for (const j of g[i]) {
216+
if (j !== fa) {
217+
dfs(j, i);
218+
}
219+
}
220+
ans[i] += cnt[k];
221+
};
222+
const ans = new Array(n).fill(0),
223+
cnt = new Array(26).fill(0);
224+
const g: number[][] = Array.from({ length: n }, () => []);
225+
for (const [a, b] of edges) {
226+
g[a].push(b);
227+
g[b].push(a);
228+
}
229+
dfs(0, -1);
230+
return ans;
231+
}
232+
```
233+
207234
### **...**
208235

209236
```

solution/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README_EN.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,33 @@ func countSubTrees(n int, edges [][]int, labels string) []int {
178178
}
179179
```
180180

181+
### **TypeScript**
182+
183+
```ts
184+
function countSubTrees(n: number, edges: number[][], labels: string): number[] {
185+
const dfs = (i: number, fa: number) => {
186+
const k = labels.charCodeAt(i) - 97;
187+
ans[i] -= cnt[k];
188+
cnt[k]++;
189+
for (const j of g[i]) {
190+
if (j !== fa) {
191+
dfs(j, i);
192+
}
193+
}
194+
ans[i] += cnt[k];
195+
};
196+
const ans = new Array(n).fill(0),
197+
cnt = new Array(26).fill(0);
198+
const g: number[][] = Array.from({ length: n }, () => []);
199+
for (const [a, b] of edges) {
200+
g[a].push(b);
201+
g[b].push(a);
202+
}
203+
dfs(0, -1);
204+
return ans;
205+
}
206+
```
207+
181208
### **...**
182209

183210
```
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
function countSubTrees(n: number, edges: number[][], labels: string): number[] {
2+
const dfs = (i: number, fa: number) => {
3+
const k = labels.charCodeAt(i) - 97;
4+
ans[i] -= cnt[k];
5+
cnt[k]++;
6+
for (const j of g[i]) {
7+
if (j !== fa) {
8+
dfs(j, i);
9+
}
10+
}
11+
ans[i] += cnt[k];
12+
};
13+
const ans = new Array(n).fill(0),
14+
cnt = new Array(26).fill(0);
15+
const g: number[][] = Array.from({ length: n }, () => []);
16+
for (const [a, b] of edges) {
17+
g[a].push(b);
18+
g[b].push(a);
19+
}
20+
dfs(0, -1);
21+
return ans;
22+
}

0 commit comments

Comments
 (0)