AlgoTales · Roadmap

DFS

Beginner · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Depth-first search explores a tree or a maze by going as deep as possible down one path, then backing up to try the next. It is a natural way to visit everything inside nested structures like folders, menus and page elements.

Practical use cases

  • Web app: Finding a file inside nested folders. A cloud storage app searches for "invoice.pdf" inside folders within folders. DFS opens a folder, goes into its first subfolder, keeps going down, then backs up and tries the next. It visits every folder exactly once and stops as soon as it finds the file.
  • Web app: Expanding a nested comment thread. A page must count or render every reply in a deep comment thread. DFS goes into a comment, then its first reply, and so on, and returns to the next sibling after finishing each branch. The thread is displayed in natural reading order.
  • System: Crawlers and task ordering. Web crawlers follow links deeply, and build tools use DFS to detect cycles and to order tasks so that a task runs only after the tasks it needs. The go-deep-then-back-up routine visits each page or task once and notices when it returns to a place it has already started.

The story: Mira in the Maze of Mehndi Lanes

During the festival season, the market near Mira's house turned into a maze of narrow lanes: mehndi stalls, bangle shops and sweet sellers, each lane splitting into more lanes. Mira had lost her mother's dupatta somewhere in the market and decided to search every stall.

Her first plan was to check the first lane for a little while, then another, then another: one stall here, one stall there. She kept losing track of where she had been. Then Mrs. Sharma, who was shopping nearby, gave her advice: "Pick one lane and walk all the way to its end. If it is a dead end, turn back to the last junction where you had another choice and take that."

Mira dropped a little coloured thread at every junction, remembering where she could return. When she hit a dead end, she went back to the most recent thread, the last junction she had passed, and tried the other lane. The most recent choice always came first: a stack.

Soon every lane in the market was searched, deeply, one branch at a time, and the dupatta turned up at a bangle shop at the far end of the left side. This "dive deep first, backtrack when stuck" way of exploring is Depth-First Search (DFS).

How to spot this problem, and where you need it

You need to visit or search through everything inside a nested structure, and exploring one branch fully before the next is natural.

Signs you need it

  • The data is nested: folders in folders, menus with submenus, categories with subcategories, replies to replies.
  • You write a function that calls itself for each child, or you struggle with loops of unknown depth.
  • The problem says "explore all paths", "find a path", "detect a cycle" or "maze".

Where to use it in a project

  • Searching, counting or rendering nested folders, menus and comment threads.
  • Checking for circular dependencies in tasks, permissions or package lists.

The solution

Start at the first node and mark it visited. Take one child and repeat the same steps on it, going deeper each time. When a node has no unvisited children, step back to its parent and take the next child. Use a function that calls itself, or a stack, to remember where to come back to. Stop early if you find what you wanted.

Payoff: Before: ad hoc loops that missed deeper levels. After: one short routine that visits every folder or reply exactly once.

Explain it like I am 8

Imagine exploring a cave with many tunnels. You pick one tunnel and keep going until it ends. Then you walk back to the last place where you could have gone another way, and try that way. "Go deep, then come back" is depth-first.

How it works, step by step

  1. Put the root on a stack (a pile where you only touch the top).
  2. Pop the top node and visit it.
  3. Push its children: the right child first and the left child last, so the left child sits on top and is visited next.
  4. Repeat: whatever you pushed most recently is explored first, so you dive deep down one branch.
  5. When a node has no children the stack top is an older item: that is your backtracking. Stop when the stack is empty.

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

// DFS with an explicit stack (the stack remembers where to come back to).
function dfs(?TreeNode $root): array {
    $order = [];
    $stack = [$root];
    while ($stack) {
        $node = array_pop($stack);          // take the top
        if ($node === null) continue;
        $order[] = $node->val;              // visit it
        $stack[] = $node->right;            // right first...
        $stack[] = $node->left;             // ...so left is on top and goes next
    }
    return $order;
}

// The same idea with recursion: the call stack does the remembering for us.
function dfsRecursive(?TreeNode $n, array &$order): void {
    if ($n === null) return;
    $order[] = $n->val;
    dfsRecursive($n->left, $order);
    dfsRecursive($n->right, $order);
}

echo implode(' ', dfs(sampleTree())) . PHP_EOL;   // 1 2 4 5 7 3 6
$o = [];
dfsRecursive(sampleTree(), $o);
echo implode(' ', $o) . PHP_EOL;                  // 1 2 4 5 7 3 6

JavaScript

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

// DFS with an explicit stack (the stack remembers where to come back to).
function dfs(root) {
  const order = [];
  const stack = [root];
  while (stack.length) {
    const node = stack.pop();           // take the top
    if (node === null) continue;
    order.push(node.val);               // visit it
    stack.push(node.right);             // right first...
    stack.push(node.left);              // ...so left is on top and goes next
  }
  return order;
}

// The same idea with recursion: the call stack does the remembering for us.
function dfsRecursive(n, order) {
  if (n === null) return;
  order.push(n.val);
  dfsRecursive(n.left, order);
  dfsRecursive(n.right, order);
}

console.log(dfs(sampleTree()).join(' '));   // 1 2 4 5 7 3 6
const o = [];
dfsRecursive(sampleTree(), o);
console.log(o.join(' '));                   // 1 2 4 5 7 3 6

Java

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

    // DFS with an explicit stack (the stack remembers where to come back to).
    static List<Integer> dfs(TreeNode root) {
        List<Integer> order = new ArrayList<>();
        Deque<TreeNode> stack = new ArrayDeque<>();
        if (root != null) stack.push(root);        // ArrayDeque refuses null, so we only push real nodes
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();           // take the top
            order.add(node.val);                   // visit it
            if (node.right != null) stack.push(node.right);   // right first...
            if (node.left != null) stack.push(node.left);     // ...so left is on top and goes next
        }
        return order;
    }

    // The same idea with recursion: the call stack does the remembering for us.
    static void dfsRecursive(TreeNode n, List<Integer> order) {
        if (n == null) return;
        order.add(n.val);
        dfsRecursive(n.left, order);
        dfsRecursive(n.right, order);
    }

    public static void main(String[] args) {
        System.out.println(join(dfs(sampleTree())));   // 1 2 4 5 7 3 6
        List<Integer> o = new ArrayList<>();
        dfsRecursive(sampleTree(), o);
        System.out.println(join(o));                   // 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
}

// dfs walks the tree with an explicit stack (the stack remembers where to come back to).
func dfs(root *TreeNode) []int {
	order := []int{}
	stack := []*TreeNode{root}
	for len(stack) > 0 {
		node := stack[len(stack)-1] // take the top
		stack = stack[:len(stack)-1]
		if node == nil {
			continue
		}
		order = append(order, node.Val)   // visit it
		stack = append(stack, node.Right) // right first...
		stack = append(stack, node.Left)  // ...so left is on top and goes next
	}
	return order
}

// dfsRecursive does the same with recursion: the call stack does the remembering for us.
func dfsRecursive(n *TreeNode, order *[]int) {
	if n == nil {
		return
	}
	*order = append(*order, n.Val)
	dfsRecursive(n.Left, order)
	dfsRecursive(n.Right, order)
}

// 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(dfs(sampleTree()), " ")) // 1 2 4 5 7 3 6
	o := []int{}
	dfsRecursive(sampleTree(), &o)
	fmt.Println(joinInts(o, " ")) // 1 2 4 5 7 3 6
}

Time: O(n) · Extra space: O(h). Every node is visited once. The stack holds roughly one path of the tree (height h) plus waiting siblings.

Watch out for

  • Pushing the left child first: with a stack, that visits the right side first (still DFS, just mirrored). Push right first to go left first.
  • Using a queue instead of a stack. A queue gives level-by-level (BFS), not deep-first.
  • Forgetting the null check when pushing children, so null values come off the stack and crash on node.val.

Quick check

  1. Which structure naturally gives depth-first order?
    • Queue
    • Stack
    • Sorted list
  2. What is the DFS visiting order of our tree (left before right)?
    • 1 2 4 5 7 3 6
    • 4 7 5 2 6 3 1
    • 1 2 3 4 5 6 7
  3. What does "backtracking" mean in DFS?
    • Deleting visited nodes
    • Starting over from the root
    • Returning to the most recent place with an unexplored option