File tree 1 file changed +41
-0
lines changed
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+
1
42
/**
2
43
* @param {number } N
3
44
* @param {number[][] } edges
You can’t perform that action at this time.
0 commit comments