← Back

🌳 Binary Tree Traversal (BFS/DFS)

Explore trees level by level or depth first

πŸ‘ΆExplain Like I'm 5

🏒 Real-Life Example: Exploring an Office Building

🌊 BFS (Breadth-First Search) = Floor by Floor

You're searching for someone in a building. BFS means you check EVERY room on Floor 1 first, then EVERY room on Floor 2, then Floor 3, and so on.

Uses a Queue (Line): β€œFirst come, first served” - like waiting in line at a store!

Perfect for finding the SHORTEST path or CLOSEST nodes!

πŸ”οΈ DFS (Depth-First Search) = One Path All the Way Down

You pick one hallway and explore it COMPLETELY to the end (all rooms, all sub-hallways) before coming back to try another hallway.

Uses a Stack (Pile): β€œLast in, first out” - like a stack of plates!

Perfect for exploring ALL possibilities or backtracking problems!

πŸ’‘ Key Difference: BFS explores neighbors first (wide), DFS explores children first (deep)!

πŸ” Code Debugger

BFS MODE
1public List<Integer> BFS(TreeNode root) {
2Queue<TreeNode> queue = new LinkedList<>();
3List<Integer> result = new ArrayList<>();
4queue.offer(root);
5while (!queue.isEmpty()) {
6TreeNode node = queue.poll();
7result.add(node.val);
8...
9if (node.left != null) queue.offer(node.left);
10if (node.right != null) queue.offer(node.right);
11}
12return result;
13}

πŸ“Š Queue:

queue:[]
visited:[]

🎯 Tree Visualization

1234567
Unvisited
In Queue
Current
Visited

Click "Start" to begin visualization

1.0x (2.0s per step)
🐌 0.3x (Very Slow)1.0x (Normal)πŸš€ 2.0x (Fast)

🌊 BFS (Java)

Queue-based
public List<Integer> BFS(TreeNode root) {
    Queue<TreeNode> queue = new LinkedList<>();
    List<Integer> result = new ArrayList<>();
    queue.offer(root);

    while (!queue.isEmpty()) {
        TreeNode node = queue.poll();
        result.add(node.val);

        if (node.left != null)
            queue.offer(node.left);
        if (node.right != null)
            queue.offer(node.right);
    }
    return result;
}

// Time: O(n), Space: O(w)

πŸ”οΈ DFS (Java)

Stack-based
public List<Integer> DFS(TreeNode root) {
    Stack<TreeNode> stack = new Stack<>();
    List<Integer> result = new ArrayList<>();
    stack.push(root);

    while (!stack.isEmpty()) {
        TreeNode node = stack.pop();
        result.add(node.val);

        if (node.right != null)
            stack.push(node.right);
        if (node.left != null)
            stack.push(node.left);
    }
    return result;
}

// Time: O(n), Space: O(h)

🎯 When to Use BFS vs DFS?

🌊 BFS (Breadth-First):

βœ…
Use When: Finding shortest path, level-order traversal, closest nodes
πŸ“Š
Problems: Binary Tree Level Order, Minimum Depth, Zigzag Level Order
πŸ’‘
Space: O(w) where w is max width of tree

πŸ”οΈ DFS (Depth-First):

βœ…
Use When: Path finding, exploring all possibilities, backtracking
πŸ“Š
Problems: Path Sum, Maximum Depth, Validate BST, Inorder Traversal
πŸ’‘
Space: O(h) where h is height of tree (usually better!)