Recursive traversal
Beginner · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Recursive traversal means writing a function that handles one node and then calls itself on the child nodes. It matches the shape of nested data perfectly, so a few lines of code can walk folders, menus, comments or HTML of any depth.
Practical use cases
- Web app: Rendering nested comment replies. A blog page shows comments, replies to replies, and so on, to any depth. A recursive function prints one comment and then calls itself for each reply, adding more indent each time. The same 10 lines handle a post with 3 comments or 3,000 without ever knowing the depth in advance.
- Web app: Building a multi-level navigation menu. The menu is stored in a database table with id and parent_id. A recursive function takes a parent id, finds its children, outputs a list item and calls itself for each child to build the dropdown inside. Admins can add a fifth level tomorrow and the code needs no change.
- System: Walking the DOM and file folders. Browsers describe a web page as a tree of tags, and a script that finds every link on the page visits each tag and its children recursively. Tools that search a disk for a file name do the same with folders inside folders.
The story: The Nesting Tiffin Boxes
Aarav's grandmother owned a set of tiffin boxes that nested inside one another. When she packed for a picnic, she did not think about all the boxes at once. She only had to say: "Open this box. Inside there are up to two smaller boxes. Do the same thing for each of them."
That was enough. The instruction "open it, then do the same for the boxes inside" took care of boxes of any size, even boxes nested ten levels deep that Grandmother had never counted. Whoever was opening a box simply paused, handed the job to the smaller boxes inside, waited for the answer, and then carried on.
The only extra rule: if a box is empty (no box inside), stop and come back. Without this rule, the opening would never finish.
This is recursion: a task that is solved by giving the same task to smaller pieces. Trees are perfect for it because every subtree is itself a smaller tree. Behind the scenes the computer remembers the paused jobs on a pile called the call stack.
How to spot this problem, and where you need it
Your data contains smaller copies of itself, like a comment with replies or a folder with sub-folders, and you do not know how deep it goes, so fixed loops cannot cover it.
Signs you need it
- Rows have a parent_id column pointing to another row of the same table, or JSON contains "children" arrays inside "children" arrays.
- You wrote loops inside loops inside loops to handle level 1, level 2 and level 3, and a user just created level 4.
- The task describes a structure as "a node with left and right parts that are also nodes", or says "for each sub-item do the same".
Where to use it in a project
- Rendering threaded comments, nested menus and category breadcrumbs from parent_id data.
- Walking JSON responses or the page DOM to find, count or transform every matching element at any depth.
The solution
Write the function so it answers a small version of the question: what to do with this one node. First handle the stopping case, an empty node, by returning at once. Otherwise do the work for the node and call the same function on each child. Trust that the call works for smaller pieces, and the whole structure gets covered.
Payoff: Before: nested loops that break at the first unexpected depth. After: one short function that works for 3 levels or 30.
Explain it like I am 8
Imagine you are told: "count the toys in this box, then ask your friend to count the toys in the box on the left, and another friend for the box on the right". Each friend does exactly the same trick for their own boxes. Everyone waits for their friends, and everything gets counted. That is recursion.
How it works, step by step
- Write one function that handles one node.
- Base case first: if the node is null, return immediately. This stops the chain.
- Do the node's own work (print it) and call the same function on the left child and on the right child.
- Where you place the own work decides the order: before the calls = preorder, between = inorder, after = postorder.
- The computer keeps a call stack: each unfinished call waits there until its children return.
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;
}
// Preorder, written recursively. $depth only helps us draw the call stack with indentation.
function traverse(?TreeNode $n, int $depth, array &$result): void {
if ($n === null) return; // base case: nothing here
echo str_repeat(' ', $depth) . 'enter ' . $n->val . PHP_EOL;
$result[] = $n->val; // the node's own work
traverse($n->left, $depth + 1, $result); // same job for the left child
traverse($n->right, $depth + 1, $result); // same job for the right child
echo str_repeat(' ', $depth) . 'leave ' . $n->val . PHP_EOL;
}
$result = [];
traverse(sampleTree(), 0, $result);
echo 'Result: ' . implode(' ', $result) . 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;
}
// Preorder, written recursively. depth only helps us draw the call stack with indentation.
function traverse(n, depth, result) {
if (n === null) return; // base case: nothing here
console.log(' '.repeat(depth) + 'enter ' + n.val);
result.push(n.val); // the node's own work
traverse(n.left, depth + 1, result); // same job for the left child
traverse(n.right, depth + 1, result); // same job for the right child
console.log(' '.repeat(depth) + 'leave ' + n.val);
}
const result = [];
traverse(sampleTree(), 0, result);
console.log('Result: ' + result.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;
}
// Preorder, written recursively. depth only helps us draw the call stack with indentation.
static void traverse(TreeNode n, int depth, List<Integer> result) {
if (n == null) return; // base case: nothing here
System.out.println(" ".repeat(depth) + "enter " + n.val);
result.add(n.val); // the node's own work
traverse(n.left, depth + 1, result); // same job for the left child
traverse(n.right, depth + 1, result); // same job for the right child
System.out.println(" ".repeat(depth) + "leave " + n.val);
}
public static void main(String[] args) {
List<Integer> result = new ArrayList<>();
traverse(sampleTree(), 0, result);
System.out.println("Result: " + result.stream().map(String::valueOf).collect(Collectors.joining(" ")));
// Result: 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
}
// traverse is preorder, written recursively. depth only helps us draw the call stack with indentation.
func traverse(n *TreeNode, depth int, result *[]int) {
if n == nil {
return // base case: nothing here
}
fmt.Println(strings.Repeat(" ", depth) + "enter " + strconv.Itoa(n.Val))
*result = append(*result, n.Val) // the node's own work
traverse(n.Left, depth+1, result) // same job for the left child
traverse(n.Right, depth+1, result) // same job for the right child
fmt.Println(strings.Repeat(" ", depth) + "leave " + strconv.Itoa(n.Val))
}
// 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() {
result := []int{}
traverse(sampleTree(), 0, &result)
fmt.Println("Result: " + joinInts(result, " ")) // Result: 1 2 4 5 7 3 6
}Time: O(n) · Extra space: O(h). Each node is entered once. The call stack is at most as deep as the tree is tall; a very tall, thin tree can run out of stack space.
Watch out for
- Forgetting the base case (
if node is null: return). The calls never stop and you get a stack overflow. - Assuming recursion is magic. Each call really is a separate waiting job; a chain 100,000 nodes long can overflow the stack.
- Modifying a shared array without making the effect clear. Pass the result list in (or return values up) so every call adds to the same place.
Quick check
- What stops a recursive tree walk from going on forever?
- The base case when the node is null
- A loop counter
- The root node
- What does the call stack hold during the walk?
- The sorted result
- The finished nodes
- The calls that are still waiting for their children
- How deep can the call stack get on our example tree?
- 7 calls
- 4 calls
- 2 calls