Go through the tree - but step by step

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();
// do my job.
...

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

+3
source share
3

, , . , , , , .

, , , , , . , , top- node , . , , .

.

+2

, collectNodes(child) , collectNodes() .

0

You can find the code to traverse the tree using an iterator step by step here

Hope this helps you.

-1
source

All Articles