How can I traverse an n
-ary tree without using recursion?
Recursive way:
traverse(Node node)
{
if(node == null)
return;
for(Node child : node.getChilds()) {
traverse(child);
}
}
How can I traverse an n
-ary tree without using recursion?
Recursive way:
traverse(Node node)
{
if(node == null)
return;
for(Node child : node.getChilds()) {
traverse(child);
}
}
You can do this without recursion and without a stack. But you need to add two extra pointers to the node:
The current child node so you know which one to take next.
With pseudocode this looks like:
What you are doing is essentially a DFS of the tree. You can eliminate recursion by using a stack:
If you want a BFS use a queue:
In case you want some other way to traverse, you'll have to follow the same approach albeit with a different data structure to store the node. Maybe a priority queue (if you want to evaluate a function at each node and then process nodes based on that value).
No language given, so in pseudo-pseudocode:
Note that this is a breadth-first traversal as opposed to the depth-first traversal given in the question. You should be able to do a depth-first traversal by
pop
ing the last item off thenodes
list instead ofshift
ing the first one.