javac TreeGraphPatterns.java && ./run --mode=interview-prep

Tree & Graph Traversal Patterns

Explore core tree and graph algorithms with animated visualizations. Understand DFS, BFS, BST validation, LCA, path sum, connected components, and topological ordering as state evolves step-by-step.

01_preorder_traversal.java
Preorder traversal visits the current node before its children: root → left → right. It is the classic DFS pattern for trees and is often used to copy or serialize a tree.
General Definition

A depth-first traversal that visits a node before its left and right subtrees, making it useful whenever you need the root information before exploring deeper branches.

Professional Definition — say this in an interview

Preorder DFS is a recursive or stack-based traversal that records the current node, then explores left and right children in that order. It runs in O(n) time because every node is visited once and uses O(h) stack space in a binary tree of height h.

Interview keywords — if you hear these, think of this pattern
preorder traversalroot firstDFStree walkrecursive traverse
SOURCE
Java
public void preorder(TreeNode root) {
    if (root == null) return;
    System.out.print(root.val + " ");
    preorder(root.left);
    preorder(root.right);
}
DEBUGGER — live watch0 / 9
831647101413
Not started
DEBUG STEPS0
Press ▶ Play or Next to start stepping through the algorithm.