n-ary tree
tree traversal
non-recursive algorithms
data structures
computer science

Traversing a n-ary tree without using recurrsion

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Recursion is the most natural way to traverse a tree, but it is not the only way. For deep trees, iterative traversal can be safer because it avoids growing the call stack. In an n-ary tree, the core idea is the same as in binary trees: use your own explicit stack for depth-first search or a queue for breadth-first search.

A Simple N-Ary Node Type

Here is a minimal Python representation:

python
1class Node:
2    def __init__(self, value, children=None):
3        self.value = value
4        self.children = children or []

The examples below assume this structure.

Iterative Depth-First Traversal

To simulate recursive preorder traversal, use a stack.

python
1def dfs_preorder(root):
2    if root is None:
3        return []
4
5    result = []
6    stack = [root]
7
8    while stack:
9        node = stack.pop()
10        result.append(node.value)
11
12        for child in reversed(node.children):
13            stack.append(child)
14
15    return result
16
17
18tree = Node(1, [
19    Node(2, [Node(5), Node(6)]),
20    Node(3),
21    Node(4),
22])
23
24print(dfs_preorder(tree))

The reversed call matters. Because a stack is last-in, first-out, reversing the child list preserves left-to-right traversal order.

Iterative Breadth-First Traversal

For level-order traversal, use a queue.

python
1from collections import deque
2
3
4def bfs(root):
5    if root is None:
6        return []
7
8    result = []
9    queue = deque([root])
10
11    while queue:
12        node = queue.popleft()
13        result.append(node.value)
14
15        for child in node.children:
16            queue.append(child)
17
18    return result
19
20
21print(bfs(tree))

This visits nodes level by level rather than depth first.

Iterative Postorder Traversal

Postorder is trickier because a node must be processed after all its children. One common iterative trick is to perform a modified preorder and reverse the result at the end.

python
1def postorder(root):
2    if root is None:
3        return []
4
5    result = []
6    stack = [root]
7
8    while stack:
9        node = stack.pop()
10        result.append(node.value)
11
12        for child in node.children:
13            stack.append(child)
14
15    return result[::-1]
16
17
18print(postorder(tree))

This works because the modified traversal visits nodes in a root-right-left-like order for n-ary trees, and reversing that gives a postorder-style result.

Why Use Iteration Instead of Recursion

The main reasons are:

  • deep trees can overflow the call stack
  • iterative code can be easier to control in constrained environments
  • explicit stacks and queues make traversal state visible

That does not mean recursion is bad. For ordinary tree depths, recursive code is often simpler. Iteration matters most when tree depth is untrusted or very large.

Space Complexity Still Exists

Avoiding recursion does not mean using no extra memory. The traversal state simply moves from the call stack into your own data structure:

  • DFS uses an explicit stack
  • BFS uses a queue

For wide trees, BFS can use more memory than DFS because many nodes from one level may be queued at once. So the traversal choice still depends on tree shape and the order you need. This matters in real systems where a very broad level can consume far more memory than the code structure suggests at first glance.

Common Pitfalls

  • Forgetting to reverse children in iterative preorder and getting the wrong visit order.
  • Assuming iterative traversal uses no extra space.
  • Choosing BFS on a very wide tree without considering queue growth.
  • Writing a postorder traversal that processes the node too early.
  • Replacing recursion with iteration without checking whether the resulting order still matches the required traversal.

Summary

  • Use a stack for iterative depth-first traversal of an n-ary tree.
  • Use a queue for breadth-first or level-order traversal.
  • Reverse child order on the stack when you want natural left-to-right preorder.
  • Iteration avoids call-stack growth but still uses explicit memory.
  • The right traversal depends on required visit order and the shape of the tree.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.