Skip to content

Commit 1403e63

Browse files
authored
Update 834-sum-of-distances-in-tree.js
1 parent 5581777 commit 1403e63

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

834-sum-of-distances-in-tree.js

+41
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,44 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @return {number[]}
5+
*/
6+
var sumOfDistancesInTree = function(n, edges) {
7+
const res = new Array(n).fill(0);
8+
const count = new Array(n).fill(1);
9+
const graph = Array.from({ length: n }, () => []);
10+
for (const [u, v] of edges) {
11+
graph[u].push(v);
12+
graph[v].push(u);
13+
}
14+
dfs1(0, -1);
15+
dfs2(0, -1);
16+
17+
return res
18+
19+
function dfs1(node, parent) {
20+
for (const child of graph[node]) {
21+
if (child === parent) {
22+
continue;
23+
}
24+
dfs1(child, node);
25+
count[node] += count[child];
26+
res[node] += res[child] + count[child];
27+
}
28+
}
29+
function dfs2(node, parent) {
30+
for (const child of graph[node]) {
31+
if (child === parent) {
32+
continue;
33+
}
34+
res[child] = res[node] - count[child] + n - count[child];
35+
dfs2(child, node);
36+
}
37+
}
38+
};
39+
40+
// another
41+
142
/**
243
* @param {number} N
344
* @param {number[][]} edges

0 commit comments

Comments
 (0)