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:
traverse(Node node) {
while (node) {
if (node->current <= MAX_CHILD) {
Node prev = node;
if (node->child[node->current]) {
node = node->child[node->current];
}
prev->current++;
} else {
// Do your thing with the node.
node->current = 0; // Reset counter for next traversal.
node = node->parent;
}
}
}