File tree Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change 641
641
830|[ Positions of Large Groups] ( ./0830-positions-of-large-groups.js ) |Easy|
642
642
831|[ Masking Personal Information] ( ./0831-masking-personal-information.js ) |Medium|
643
643
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|
644
645
841|[ Keys and Rooms] ( ./0841-keys-and-rooms.js ) |Medium|
645
646
844|[ Backspace String Compare] ( ./0844-backspace-string-compare.js ) |Easy|
646
647
846|[ Hand of Straights] ( ./0846-hand-of-straights.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments