Iterative traversal
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Iterative traversal walks a tree with a loop and your own stack (a pile where you add and remove from the top) instead of function calls that call themselves. You get the same visiting order, but you control memory and can pause or resume the walk.
Practical use cases
- Web app: Crash on a very deep category tree. An import script walks a category tree that someone generated with 50,000 levels, and the recursive version dies with a "maximum call stack size exceeded" error. Rewriting the walk with an array used as a stack keeps the pending nodes in ordinary memory instead. The import finishes instead of crashing the server.
- Web app: Lazy loading in a tree view. A file-browser widget in React shows folders and loads the next item only when the user scrolls or presses "next". With an explicit stack the walk can stop after any item and carry on later from exactly the same place. Recursion cannot be paused like that.
- System: Iterators and search in huge structures. Language features like generators and "next()" iterators on ordered maps are built on a saved stack of places still to visit. Tools that scan very deep directory trees also avoid recursion so they never run out of call space. This matters on servers, where one crash on a deep input can take a whole request or job down.
The story: Zoya's Own Bookmarks
Zoya was reading a thick storybook full of "go to page X" instructions. The book's trick was to leave the reader inside a story inside a story inside a story. Normally, her friend Aarav would just let the book remember where each story had been paused. But Zoya's book had so many nested stories that the book ran out of space and refused to go deeper.
Mira suggested: "Do not rely on the book to remember. Keep your own pile of bookmarks." Every time Zoya dived into a deeper story, she slipped a bookmark in her pile. When a story was over, she took the top bookmark, returned to that place, and carried on.
It was the same journey: deeper, back, deeper, back. But now Zoya controlled the pile of bookmarks herself, and she could make it as big as she wanted. No more "too deep" errors.
That is iterative traversal. Recursion hides a stack the computer manages for you; in iterative code you create the stack yourself, and use a plain while loop. The visiting order is exactly the same as the recursive version.
How to spot this problem, and where you need it
A recursive walk crashes on deep data, or you need to stop and restart a walk, or hand back one item at a time, which plain recursion cannot do.
Signs you need it
- You see errors such as "Maximum call stack size exceeded" or "Allowed memory size exhausted" when running a recursive function on large nested data.
- You need a "next item" button, a generator, or an iterator that gives one node per call.
- The interviewer or task says "do it without recursion" or "manage the pending nodes yourself with a stack".
Where to use it in a project
- Importers and migration scripts that process user-created hierarchies of unknown depth.
- UI components that step through a tree one item at a time, such as keyboard navigation in a tree menu.
The solution
Create an empty stack and push the starting node. While the stack is not empty, pop the top node, handle it, and push its children (in reverse order if you need left-to-right). For inorder, keep pushing left children until none remain, pop one, handle it, then move to its right child. The stack takes the place of the hidden call stack.
Payoff: Before: a crash at about 10,000 levels deep. After: the same walk finishes at any depth the memory allows, and can pause between items.
Explain it like I am 8
Recursion is like asking the computer to remember your place in every game it plays. Iterative is when you keep your own little pile of sticky notes: "come back to this one later". You pick the top note when you are ready to return. Same game, but you hold the notes.
How it works, step by step
- Make an empty stack and a pointer
curthat starts at the root. - While
curis not null, push it and movecurto its left child (go as far left as possible). - When you cannot go left, pop the top of the stack: that is the next node to visit. Visit it.
- Set
curto the popped node's right child and go back to step 2. - Stop when
curis null and the stack is empty. Preorder works the same way with a simpler loop: pop, visit, push right, push left.
The code in four languages
PHP
<?php
class TreeNode {
public ?TreeNode $left = null;
public ?TreeNode $right = null;
public function __construct(public int $val) {}
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
function sampleTree(): TreeNode {
$root = new TreeNode(1);
$root->left = new TreeNode(2);
$root->right = new TreeNode(3);
$root->left->left = new TreeNode(4);
$root->left->right = new TreeNode(5);
$root->right->right = new TreeNode(6);
$root->left->right->left = new TreeNode(7);
return $root;
}
// Inorder (Left, Root, Right) with our own stack: no recursion.
function inorderIterative(?TreeNode $root): array {
$out = [];
$stack = [];
$cur = $root;
while ($cur !== null || $stack) {
while ($cur !== null) { // go left as far as possible
$stack[] = $cur; // remember we owe this node a visit
$cur = $cur->left;
}
$cur = array_pop($stack); // dead end: take the latest remembered node
$out[] = $cur->val; // visit it
$cur = $cur->right; // then explore its right side
}
return $out;
}
// Preorder (Root, Left, Right) with a stack: pop, visit, push right then left.
function preorderIterative(?TreeNode $root): array {
$out = [];
$stack = $root ? [$root] : [];
while ($stack) {
$n = array_pop($stack);
$out[] = $n->val;
if ($n->right) $stack[] = $n->right;
if ($n->left) $stack[] = $n->left; // left on top, so it goes first
}
return $out;
}
echo implode(' ', inorderIterative(sampleTree())) . PHP_EOL; // 4 2 7 5 1 3 6
echo implode(' ', preorderIterative(sampleTree())) . PHP_EOL; // 1 2 4 5 7 3 6JavaScript
class TreeNode {
constructor(val) { this.val = val; this.left = null; this.right = null; }
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
function sampleTree() {
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
root.left.right.left = new TreeNode(7);
return root;
}
// Inorder (Left, Root, Right) with our own stack: no recursion.
function inorderIterative(root) {
const out = [];
const stack = [];
let cur = root;
while (cur !== null || stack.length) {
while (cur !== null) { // go left as far as possible
stack.push(cur); // remember we owe this node a visit
cur = cur.left;
}
cur = stack.pop(); // dead end: take the latest remembered node
out.push(cur.val); // visit it
cur = cur.right; // then explore its right side
}
return out;
}
// Preorder (Root, Left, Right) with a stack: pop, visit, push right then left.
function preorderIterative(root) {
const out = [];
const stack = root ? [root] : [];
while (stack.length) {
const n = stack.pop();
out.push(n.val);
if (n.right) stack.push(n.right);
if (n.left) stack.push(n.left); // left on top, so it goes first
}
return out;
}
console.log(inorderIterative(sampleTree()).join(' ')); // 4 2 7 5 1 3 6
console.log(preorderIterative(sampleTree()).join(' ')); // 1 2 4 5 7 3 6Java
import java.util.*;
import java.util.stream.*;
public class Main {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
// The example tree: 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
static TreeNode sampleTree() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
root.left.right.left = new TreeNode(7);
return root;
}
static String join(List<Integer> xs) {
return xs.stream().map(String::valueOf).collect(Collectors.joining(" "));
}
// Inorder (Left, Root, Right) with our own stack: no recursion.
static List<Integer> inorderIterative(TreeNode root) {
List<Integer> out = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) { // go left as far as possible
stack.push(cur); // remember we owe this node a visit
cur = cur.left;
}
cur = stack.pop(); // dead end: take the latest remembered node
out.add(cur.val); // visit it
cur = cur.right; // then explore its right side
}
return out;
}
// Preorder (Root, Left, Right) with a stack: pop, visit, push right then left.
static List<Integer> preorderIterative(TreeNode root) {
List<Integer> out = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
if (root != null) stack.push(root);
while (!stack.isEmpty()) {
TreeNode n = stack.pop();
out.add(n.val);
if (n.right != null) stack.push(n.right);
if (n.left != null) stack.push(n.left); // left on top, so it goes first
}
return out;
}
public static void main(String[] args) {
System.out.println(join(inorderIterative(sampleTree()))); // 4 2 7 5 1 3 6
System.out.println(join(preorderIterative(sampleTree()))); // 1 2 4 5 7 3 6
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
type TreeNode struct {
Val int
Left, Right *TreeNode
}
// The example tree: 1
//
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
func sampleTree() *TreeNode {
root := &TreeNode{Val: 1}
root.Left = &TreeNode{Val: 2}
root.Right = &TreeNode{Val: 3}
root.Left.Left = &TreeNode{Val: 4}
root.Left.Right = &TreeNode{Val: 5}
root.Right.Right = &TreeNode{Val: 6}
root.Left.Right.Left = &TreeNode{Val: 7}
return root
}
// inorderIterative does Left, Root, Right with our own stack: no recursion.
func inorderIterative(root *TreeNode) []int {
out := []int{}
stack := []*TreeNode{}
cur := root
for cur != nil || len(stack) > 0 {
for cur != nil { // go left as far as possible
stack = append(stack, cur) // remember we owe this node a visit
cur = cur.Left
}
cur = stack[len(stack)-1] // dead end: take the latest remembered node
stack = stack[:len(stack)-1]
out = append(out, cur.Val) // visit it
cur = cur.Right // then explore its right side
}
return out
}
// preorderIterative does Root, Left, Right with a stack: pop, visit, push right then left.
func preorderIterative(root *TreeNode) []int {
out := []int{}
stack := []*TreeNode{}
if root != nil {
stack = append(stack, root)
}
for len(stack) > 0 {
n := stack[len(stack)-1]
stack = stack[:len(stack)-1]
out = append(out, n.Val)
if n.Right != nil {
stack = append(stack, n.Right)
}
if n.Left != nil {
stack = append(stack, n.Left) // left on top, so it goes first
}
}
return out
}
// joinInts glues the numbers together with a separator.
func joinInts(xs []int, sep string) string {
parts := make([]string, len(xs))
for i, v := range xs {
parts[i] = strconv.Itoa(v)
}
return strings.Join(parts, sep)
}
func main() {
fmt.Println(joinInts(inorderIterative(sampleTree()), " ")) // 4 2 7 5 1 3 6
fmt.Println(joinInts(preorderIterative(sampleTree()), " ")) // 1 2 4 5 7 3 6
}Time: O(n) · Extra space: O(h). Each node is pushed and popped once. The stack holds one path from the root down, so it is as tall as the tree.
Watch out for
- Stopping the outer loop when only
curis null. You must also check that the stack is empty, or you miss every node waiting on it. - Forgetting to move to the popped node's right child after visiting it, which skips the whole right subtree.
- Pushing the left child before the right in the iterative preorder. The stack then returns the right child first and the order is mirrored.
Quick check
- What does iterative traversal use in place of recursion?
- A queue
- Our own stack with a loop
- A sorted list
- In iterative inorder, when do you visit a node?
- When you pop it
- After its parent is popped
- When you push it
- Why choose the iterative version over the recursive one?
- It uses no memory
- It is always faster
- It cannot overflow the call stack on very deep trees