Skip to content

Commit 3045bda

Browse files
author
lennart
committed
add Test for forEachAncestor
1 parent 57be79f commit 3045bda

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

src/main/java/com/thealgorithms/tree/CentroidDecomposition.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ public void findCentroid(int src, int previousCentroid){
162162
* Applies the given action to all centroid ancestors of the given node,
163163
* including the node itself, walking up via centroidParent[] until the root.
164164
*/
165-
public void forEachAcestor(int centroid, IntConsumer action){
165+
public void forEachAncestor(int centroid, IntConsumer action){
166166
int curr = centroid;
167167
while(curr != -1){
168168
action.accept(curr);

src/test/java/com/thealgorithms/tree/CentroidDecompositionTest.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,30 @@ void resetClearsCentroidData() {
174174
assertEquals(0, cd.getParent(11));
175175
}
176176

177+
178+
@Test
179+
void forEachAncestorVisitsCorrectChain() {
180+
cd.build();
181+
182+
int[] testNodes = {0, 3, 7, 11, 15};
183+
184+
for (int node : testNodes) {
185+
186+
List<Integer> visited = new ArrayList<>();
187+
cd.forEachAncestor(node, visited::add);
188+
189+
List<Integer> expected = new ArrayList<>();
190+
int curr = node;
191+
while (curr != -1) {
192+
expected.add(curr);
193+
curr = cd.getParent(curr);
194+
}
195+
196+
assertEquals(expected, visited,
197+
"forEachAncestor wrong for node " + node);
198+
}
199+
}
200+
177201
@Test
178202
void buildingFromDifferentStartNodesYieldsValidTrees() {
179203
CentroidDecomposition a = new CentroidDecomposition(16, 0);

0 commit comments

Comments
 (0)