Skip to content

Commit 12c8b48

Browse files
committedMar 19, 2025
Add solution #834
1 parent 6890405 commit 12c8b48

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,7 @@
641641
830|[Positions of Large Groups](./0830-positions-of-large-groups.js)|Easy|
642642
831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium|
643643
833|[Find And Replace in String](./0833-find-and-replace-in-string.js)|Medium|
644+
834|[Sum of Distances in Tree](./0834-sum-of-distances-in-tree.js)|Hard|
644645
841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium|
645646
844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy|
646647
846|[Hand of Straights](./0846-hand-of-straights.js)|Medium|
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* 834. Sum of Distances in Tree
3+
* https://leetcode.com/problems/sum-of-distances-in-tree/
4+
* Difficulty: Hard
5+
*
6+
* There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
7+
*
8+
* You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there
9+
* is an edge between nodes ai and bi in the tree.
10+
*
11+
* Return an array answer of length n where answer[i] is the sum of the distances between the ith
12+
* node in the tree and all other nodes.
13+
*/
14+
15+
/**
16+
* @param {number} n
17+
* @param {number[][]} edges
18+
* @return {number[]}
19+
*/
20+
var sumOfDistancesInTree = function(n, edges) {
21+
const graph = Array.from({ length: n }, () => []);
22+
const count = new Array(n).fill(1);
23+
const result = new Array(n).fill(0);
24+
25+
for (const [a, b] of edges) {
26+
graph[a].push(b);
27+
graph[b].push(a);
28+
}
29+
30+
function dfs1(node, parent) {
31+
for (const child of graph[node]) {
32+
if (child !== parent) {
33+
dfs1(child, node);
34+
count[node] += count[child];
35+
result[node] += result[child] + count[child];
36+
}
37+
}
38+
}
39+
40+
function dfs2(node, parent) {
41+
for (const child of graph[node]) {
42+
if (child !== parent) {
43+
result[child] = result[node] - count[child] + (n - count[child]);
44+
dfs2(child, node);
45+
}
46+
}
47+
}
48+
49+
dfs1(0, -1);
50+
dfs2(0, -1);
51+
52+
return result;
53+
};

0 commit comments

Comments
 (0)
Please sign in to comment.