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: Morris Traversal Morris Traversal is a method based on the idea of a threaded binary tree and can be used to traverse a tree without using recursion or stack.
Recursive functions are simpler to implement since you only have to care about a node, they use the stack to store the state for each call. Non-recursive functions have a lot less stack usage but require you to store a list of all nodes for each level and can be far more complex than recursive functions.
What you are doing is essentially a DFS of the tree. You can eliminate recursion by using a stack:
traverse(Node node) { if (node==NULL) return; stack<Node> stk; stk.push(node); while (!stk.empty()) { Node top = stk.pop(); for (Node child in top.getChildren()) { stk.push(child); } process(top); } }
If you want a BFS use a queue:
traverse(Node node) { if (node==NULL) return; queue<Node> que; que.addRear(node); while (!que.empty()) { Node front = que.deleteFront(); for (Node child in front.getChildren()) { que.addRear(child); } process(front); } }
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).
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; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With