AlgoViz

Tree DFS

easy 18 min

Depth-first search walks a tree by going as deep as possible down one branch before backing up to try the next.

Where it shows up

The same pattern appears across everyday software.

  • File systems and disk usage

    Listing a directory tree (`find`, `tree`) is a preorder walk: print the folder, then its contents. Totalling folder sizes (`du`) is postorder: a folder's size is known only after all its children are summed. Deleting a folder recursively is also postorder.

  • Compilers and expression trees

    A compiler parses code into a syntax tree and walks it depth-first: postorder to evaluate or generate code for an expression (operands before the operator), preorder for prefix forms. Linters and code formatters traverse the same trees.

  • Web pages and the DOM

    The browser's DOM is a tree. `querySelectorAll` returns elements in document order, which is a preorder DFS. Mirroring a layout for right-to-left languages swaps the order of children at every level, the same move as inverting a binary tree.

  • Databases and sorted indexes

    Database indexes are search trees (B-trees). A range scan such as `WHERE price BETWEEN 10 AND 50` walks the keys in sorted order, the inorder idea applied to a tree with many keys per node.

  • Game AI and puzzle solving

    Game engines explore decision trees of moves depth-first (minimax with alpha-beta pruning) because DFS keeps only one line of play in memory. Maze and Sudoku solvers use DFS with backtracking: try a choice, go deep, undo it on a dead end.

  • Dependency resolution

    Build tools and package managers order tasks with a DFS over the dependency graph: a task is emitted after all of its dependencies finish, which is postorder, and reversing it gives a topological order. A visited set catches circular dependencies.