12
12
13
13
public class TreeCenterLongestPathImpl {
14
14
15
- private static int [] dfs (
15
+ private static class DfsResult {
16
+ // The distance to the furthest node (from where the DFS started)
17
+ int distance ;
18
+
19
+ // The index of the furthest node (from where the DFS started)
20
+ int index ;
21
+
22
+ public DfsResult (int distance , int index ) {
23
+ this .distance = distance ;
24
+ this .index = index ;
25
+ }
26
+ }
27
+
28
+ private static DfsResult dfs (
16
29
List <List <Integer >> graph , boolean [] visited , int [] prev , int at , int parent ) {
17
30
18
31
// Already visited this node
19
- if (visited [at ]) return new int [] { 0 , parent } ;
32
+ if (visited [at ]) return new DfsResult ( 0 , parent ) ;
20
33
21
34
// Visit this node
22
35
visited [at ] = true ;
@@ -28,15 +41,15 @@ private static int[] dfs(
28
41
List <Integer > edges = graph .get (at );
29
42
30
43
for (int to : edges ) {
31
- int [] tuple = dfs (graph , visited , prev , to , at );
32
- int dist = tuple [ 0 ] + 1 ;
44
+ DfsResult result = dfs (graph , visited , prev , to , at );
45
+ int dist = result . distance + 1 ;
33
46
if (dist > bestDist ) {
34
47
bestDist = dist ;
35
- index = tuple [ 1 ] ;
48
+ index = result . index ;
36
49
}
37
50
}
38
51
39
- return new int [] { bestDist , index } ;
52
+ return new DfsResult ( bestDist , index ) ;
40
53
}
41
54
42
55
public static List <Integer > findTreeCenters (List <List <Integer >> graph ) {
@@ -48,7 +61,8 @@ public static List<Integer> findTreeCenters(List<List<Integer>> graph) {
48
61
int [] prev = new int [n ];
49
62
50
63
// Do DFS to find furthest node from the start
51
- int furthestNode1 = dfs (graph , visited , prev , 0 , -1 )[1 ];
64
+ DfsResult result = dfs (graph , visited , prev , 0 , -1 );
65
+ int furthestNode1 = result .index ;
52
66
53
67
// Singleton
54
68
if (furthestNode1 == -1 ) {
@@ -59,7 +73,9 @@ public static List<Integer> findTreeCenters(List<List<Integer>> graph) {
59
73
// Do another DFS, but this time from the furthest node.
60
74
Arrays .fill (visited , false );
61
75
Arrays .fill (prev , 0 );
62
- int furthestNode2 = dfs (graph , visited , prev , furthestNode1 , -1 )[1 ];
76
+
77
+ result = dfs (graph , visited , prev , furthestNode1 , -1 );
78
+ int furthestNode2 = result .index ;
63
79
64
80
List <Integer > path = new LinkedList <>();
65
81
for (int i = furthestNode2 ; i != -1 ; i = prev [i ]) {
0 commit comments