File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-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 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
+ }
Original file line number Diff line number Diff line change 249
249
- [ 817 Linked List Components] ( ./817/main.js )
250
250
- [ 832 Flipping an Image] ( ./832/main.js )
251
251
- [ 833 Find And Replace in String] ( ./833/main.js )
252
+ - [ 834 Sum of Distances in Tree] ( ./834/main.js )
252
253
- [ 835 Image Overlap] ( ./835/main.js )
253
254
254
255
* Q: What is ` LZS ` ? It almost appears inside all files (like js, cpp)?*
You can’t perform that action at this time.
0 commit comments