Skip to content

Commit 6586caf

Browse files
William FisetWilliam Fiset
William Fiset
authored and
William Fiset
committed
Simplify Euler tour LCA
1 parent bbeacd9 commit 6586caf

File tree

1 file changed

+26
-25
lines changed

1 file changed

+26
-25
lines changed

src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/LowestCommonAncestorEulerTour.java

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,10 @@ public String toString() {
9797
}
9898
}
9999

100-
private int n;
101-
private TreeNode root;
100+
private final int n;
101+
private final TreeNode root;
102+
103+
private int index = 0;
102104
private boolean preprocessed;
103105

104106
// Populated when constructing Euler Tour.
@@ -125,14 +127,34 @@ private void preprocess() {
125127
last = new int[n];
126128

127129
// Do depth first search to construct Euler tour.
128-
dfs(root, 0, 0);
130+
dfs(root, 0);
129131

130132
// Initialize and build sparse table on the heights which will allow us to
131133
// index into the nodeOrder array to return the LCA.
132134
sparseTable = new MinSparseTable(heights);
133135
}
134136

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.
136158
public TreeNode lca(int id1, int id2) {
137159
// Lazily preprocess here instead of in constructor.
138160
if (!preprocessed) {
@@ -146,27 +168,6 @@ public TreeNode lca(int id1, int id2) {
146168
return nodeOrder[i];
147169
}
148170

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-
170171
// Sparse table for efficient minimum range queries in O(1) with O(nlogn) space
171172
private static class MinSparseTable {
172173

0 commit comments

Comments
 (0)