Skip to content

Commit 7e810e2

Browse files
committed
834
1 parent 2ab827c commit 7e810e2

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

834/main.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @param {number} N
3+
* @param {number[][]} edges
4+
* @return {number[]}
5+
*/
6+
var sumOfDistancesInTree = function (N, edges) {
7+
const conn = Array.from({length: N}, () => [])
8+
const nodes = Array.from({length: N + 1}, () => ({}))
9+
const disOfSubTree = Array.from({length: N + 1}, () => ({}))
10+
for (const [a, b] of edges) {
11+
conn[a].push(b)
12+
conn[b].push(a)
13+
nodes[a][b] = -1
14+
nodes[b][a] = -1
15+
disOfSubTree[a][b] = -1
16+
disOfSubTree[b][a] = -1
17+
}
18+
19+
function helper (cur, from) {
20+
if (nodes[from][cur] != null && nodes[from][cur] !== -1) {
21+
return {
22+
dis: disOfSubTree[from][cur],
23+
nodeCnt: nodes[from][cur]
24+
}
25+
}
26+
nodes[from][cur] = 0
27+
disOfSubTree[from][cur] = 0
28+
for (const next of conn[cur]) {
29+
if (next === from) {
30+
continue
31+
}
32+
const {dis, nodeCnt} = helper(next, cur)
33+
nodes[from][cur] += nodeCnt + 1
34+
disOfSubTree[from][cur] += dis + 1 + nodeCnt
35+
}
36+
return {
37+
dis: disOfSubTree[from][cur],
38+
nodeCnt: nodes[from][cur]
39+
}
40+
}
41+
42+
const ans = []
43+
for (let i = 0; i < N; i++) {
44+
ans.push(helper(i, N).dis)
45+
}
46+
return ans
47+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,7 @@
249249
- [817 Linked List Components](./817/main.js)
250250
- [832 Flipping an Image](./832/main.js)
251251
- [833 Find And Replace in String](./833/main.js)
252+
- [834 Sum of Distances in Tree](./834/main.js)
252253
- [835 Image Overlap](./835/main.js)
253254

254255
*Q: What is `LZS`? It almost appears inside all files (like js, cpp)?*

0 commit comments

Comments
 (0)