Files
Testate/WS2425/Testat 3b/TreeVisitor.java
T
2025-07-21 16:03:34 +02:00

73 lines
1.5 KiB
Java

import java.util.ArrayList;
import java.util.List;
/**
* A visitor to test the implementation.
*
* @author Marcus
*/
public class TreeVisitor {
/**
* The list of visited tree nodes.
*/
private List<TreeNode> visited = new ArrayList<>();
/**
* Creates a new visitor with an empty list of nodes.
*/
public TreeVisitor() {
super();
}
/**
* Returns the list with the visited nodes.
*
* @return The visited nodes.
*/
public List<TreeNode> getVisited() {
return visited;
}
/**
* Visits the tree node and adds it to the list
* of visited nodes.
*
* @param node The node to visit.
*/
public void visit(TreeNode node) {
visited.add(node);
}
/**
* Converts the visited node list into an int
* array containing the values of the nodes.
*
* @return The array with the node values.
*/
public double[] toArray() {
double[] result = new double[visited.size()];
for (int i = 0; i < result.length; i++) {
//Added null check - otherwise Jack test crash
if(visited.get(i) == null) result[i] = Integer.MAX_VALUE;
else result[i] = visited.get(i).getValue();
}
return result;
}
@Override
public String toString() {
String result = "";
for (int i = 0; i < visited.size(); i++) {
//Added null check - otherwise Jack test crash
if(visited.get(i) == null) result += "[NULL]";
else result += visited.get(i).getValue();
if (i != visited.size() - 1) {
result += ", ";
}
}
return result;
}
}