File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][] } edges
3
+ * @return {number }
4
+ */
5
+ const treeDiameter = function ( edges ) {
6
+ const graph = { }
7
+ for ( const [ u , v ] of edges ) {
8
+ if ( graph [ u ] == null ) graph [ u ] = new Set ( )
9
+ if ( graph [ v ] == null ) graph [ v ] = new Set ( )
10
+ graph [ u ] . add ( v )
11
+ graph [ v ] . add ( u )
12
+ }
13
+
14
+ let res = 0
15
+
16
+ dfs ( 0 , - 1 )
17
+
18
+ return res
19
+
20
+ function dfs ( node , parent ) {
21
+ let first = 0 , sec = 0
22
+
23
+ for ( const nxt of ( graph [ node ] || [ ] ) ) {
24
+ if ( nxt === parent ) continue
25
+ const childNum = dfs ( nxt , node )
26
+ if ( childNum > first ) {
27
+ sec = first
28
+ first = childNum
29
+ } else if ( childNum > sec ) {
30
+ sec = childNum
31
+ }
32
+ }
33
+
34
+ const nodeNum = first + sec + 1
35
+ res = Math . max ( res , nodeNum - 1 )
36
+ return first + 1
37
+ }
38
+ }
You can’t perform that action at this time.
0 commit comments