How can I traverse an n-ary tree without using recursion?
Recursive way:
traverse(Node node)
{
if(node == null)
return;
No language given, so in pseudo-pseudocode:
traverse(Node node)
{
List nodes = [node];
while (nodes.notEmpty) {
Node n = nodes.shift();
for (Node child in n.getChildren()) {
nodes.add(child);
}
// do stuff with n, maybe
}
}
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 poping the last item off the nodes list instead of shifting the first one.