@@ -97,8 +97,10 @@ public String toString() {
97
97
}
98
98
}
99
99
100
- private int n ;
101
- private TreeNode root ;
100
+ private final int n ;
101
+ private final TreeNode root ;
102
+
103
+ private int index = 0 ;
102
104
private boolean preprocessed ;
103
105
104
106
// Populated when constructing Euler Tour.
@@ -125,14 +127,34 @@ private void preprocess() {
125
127
last = new int [n ];
126
128
127
129
// Do depth first search to construct Euler tour.
128
- dfs (root , 0 , 0 );
130
+ dfs (root , 0 );
129
131
130
132
// Initialize and build sparse table on the heights which will allow us to
131
133
// index into the nodeOrder array to return the LCA.
132
134
sparseTable = new MinSparseTable (heights );
133
135
}
134
136
135
- // Finds the lowest common ancestor of the nodeOrder with id1 and id2.
137
+ private void visit (TreeNode node , long height ) {
138
+ nodeOrder [index ] = node ;
139
+ heights [index ] = height ;
140
+ last [node .id ()] = index ;
141
+ index ++;
142
+ }
143
+
144
+ // Construct Euler Tour by populating the 'heights' and 'nodeOrder' arrays.
145
+ private void dfs (TreeNode node , long height ) {
146
+ if (node == null ) {
147
+ return ;
148
+ }
149
+
150
+ visit (node , height );
151
+ for (TreeNode child : node .children ()) {
152
+ dfs (child , height + 1 );
153
+ visit (node , height );
154
+ }
155
+ }
156
+
157
+ // Finds the lowest common ancestor of the nodes id1 and id2.
136
158
public TreeNode lca (int id1 , int id2 ) {
137
159
// Lazily preprocess here instead of in constructor.
138
160
if (!preprocessed ) {
@@ -146,27 +168,6 @@ public TreeNode lca(int id1, int id2) {
146
168
return nodeOrder [i ];
147
169
}
148
170
149
- // Construct Euler Tour by populating the 'heights' and 'nodeOrder' arrays.
150
- private int dfs (TreeNode node , long height , int index ) {
151
- if (node == null ) {
152
- return index ;
153
- }
154
- nodeOrder [index ] = node ;
155
- heights [index ] = height ;
156
- last [node .id ()] = index ;
157
- index ++;
158
-
159
- for (TreeNode child : node .children ()) {
160
- index = dfs (child , height + 1 , index );
161
-
162
- nodeOrder [index ] = node ;
163
- heights [index ] = height ;
164
- last [node .id ()] = index ;
165
- index ++;
166
- }
167
- return index ;
168
- }
169
-
170
171
// Sparse table for efficient minimum range queries in O(1) with O(nlogn) space
171
172
private static class MinSparseTable {
172
173
0 commit comments