algorithmtree-traversal

Traversing a n-ary tree without using recurrsion


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);
    }
}

Solution

  • You can do this without recursion and without a stack. But you need to add two extra pointers to the node:

    1. The parent node. So you can come back to the parent if you are finished.
    2. The current child node so you know which one to take next.

      • For each node, you handle all the kids.
      • If a kid is handled, you check if there is a next kid and handle that (updating the current).
      • If all kids are handled, go back to the parent.
      • If the node is NULL, quit.

    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;
        }
      }
    }