🌳 Binary Tree Patterns

DFS/BFS Traversals & Path Problems

Day 5/6 Pattern: Tree Traversal

📖 Pattern Overview

🎯 When to Use

  • Tree traversal (all types)
  • Path sum problems
  • Lowest common ancestor
  • Tree serialization

⚡ Complexity

  • Time: O(n)
  • Space: O(h) - height
  • DFS: Recursion stack
  • BFS: Queue size

🔑 Traversal Types

  • Inorder: Left → Root → Right
  • Preorder: Root → Left → Right
  • Postorder: Left → Right → Root
  • Level Order: BFS layer by layer

🎯 Select Visualization

Binary Tree Traversals

Normal

Traversal Result:

[]

Current Step:

Click "Start" to begin tree traversal

📚 LeetCode Problems

94. Binary Tree Inorder Traversal

Easy

Return inorder traversal of tree (iterative & recursive).

Solve on LeetCode →

102. Binary Tree Level Order

Medium

Return level order traversal (BFS).

Solve on LeetCode →

112. Path Sum

Easy

Check if tree has root-to-leaf path with given sum.

Solve on LeetCode →

113. Path Sum II

Medium

Find all root-to-leaf paths with given sum.

Solve on LeetCode →

103. Zigzag Level Order

Medium

Return zigzag level order traversal.

Solve on LeetCode →

236. Lowest Common Ancestor

Medium

Find LCA of two nodes in binary tree.

Solve on LeetCode →

🧠 Algorithm Deep Dive

DFS Traversals (Recursive)

// Inorder: Left → Root → Right
function inorder(root) {
    if (!root) return;
    inorder(root.left);
    visit(root);
    inorder(root.right);
}

// Preorder: Root → Left → Right
function preorder(root) {
    if (!root) return;
    visit(root);
    preorder(root.left);
    preorder(root.right);
}

// Postorder: Left → Right → Root
function postorder(root) {
    if (!root) return;
    postorder(root.left);
    postorder(root.right);
    visit(root);
}

BFS Level Order (Iterative)

function levelOrder(root) {
    if (!root) return [];
    
    const result = [];
    const queue = [root];
    
    while (queue.length > 0) {
        const levelSize = queue.length;
        const currentLevel = [];
        
        for (let i = 0; i < levelSize; i++) {
            const node = queue.shift();
            currentLevel.push(node.val);
            
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }
        
        result.push(currentLevel);
    }
    
    return result;
}

Path Sum

function hasPathSum(root, targetSum) {
    if (!root) return false;
    
    // Leaf node
    if (!root.left && !root.right) {
        return root.val === targetSum;
    }
    
    // Recurse with reduced sum
    const remaining = targetSum - root.val;
    return hasPathSum(root.left, remaining) || 
           hasPathSum(root.right, remaining);
}

Real-World Applications

  • File Systems: Directory traversal (DFS/BFS)
  • DOM Manipulation: HTML element traversal
  • Organization Charts: Employee hierarchy
  • Compilers: Abstract syntax tree traversal
  • Databases: B-tree index traversal
  • AI/ML: Decision tree evaluation