I have the following code to move a tree (pre-order):
public void traverse(Node node) {
visit(node);
for (Node child : node.getChildren()) {
traverse(child);
}
}
I would like a step-by-step move. something like Iterator, so that the client (the caller), which may be another application, can control the progress. (for example: in the user interface, we have a "Next" button, and by clicking on this button, we should visit the next node)
my current solution looks something like this:
List<Node> nodes = new ArrayList<Node>();
collectNodes(root, nodes);
Iterator<Node> it = nodes.iterator();
...
public void collectNodes(Node node, List<Node> nodes) {
nodes.add(node);
for (Node child : node.getChildren()) {
collectNodes(child, nodes);
}
}
As you can see in the code, I visit all the nodes (in collectNodes) to collect and place them in a list in pre-order format.
I was wondering if there is any solution without this extra (collectNodes) iteration?
Regards, Mohammad
source
share