Why trees are everywhere in interviews
Trees appear in roughly 25% of FAANG interview problems. They test recursion naturally, have multiple traversal orders (pre/in/post/level), and combine well with other patterns (DP, BFS, hash maps). The good news: most tree problems are variations of 5–6 core patterns. Master those patterns and you can handle any tree problem.
Pattern 1: DFS traversal
The foundation. Preorder (root → left → right) for serialization. Inorder (left → root → right) gives sorted order in BSTs. Postorder (left → right → root) when you need children's results before processing the parent — height, diameter, balanced check. Key problems: Maximum Depth (LC 104), Invert Binary Tree (LC 226), Path Sum (LC 112), Diameter of Binary Tree (LC 543), Balanced Binary Tree (LC 110).
Pattern 2: BFS / level order
Use a queue. Process nodes level by level. Essential for: shortest path in a tree, level averages, right-side view, zigzag traversal. The template: push root, while queue not empty → process all nodes at current level, push their children. Key problems: Level Order Traversal (LC 102), Right Side View (LC 199), Average of Levels (LC 637), Maximum Width (LC 662).
Pattern 3: Path problems
These are the trickiest. The key insight: in a tree, a path can go through any node. A recursive function typically returns the best path through the current node upward (to parent), but also considers the path that passes through the current node (left branch + node + right branch) as a potential global answer. Key problems: Binary Tree Maximum Path Sum (LC 124) — most asked at FAANG. Path Sum II (LC 113). Sum Root to Leaf Numbers (LC 129).
Pattern 4: BST operations
BSTs give O(log n) search, insert, delete by maintaining the invariant: left < node < right. In-order traversal always gives sorted order — use this to validate BSTs or find kth smallest. Key problems: Validate BST (LC 98), Kth Smallest in BST (LC 230), Lowest Common Ancestor in BST (LC 235), Insert into BST (LC 701), Delete Node in BST (LC 450).
Pattern 5: LCA and ancestor problems
Lowest Common Ancestor is a flagship problem. For BSTs: if both targets are less than root, go left; if both greater, go right; otherwise root is LCA. For general trees: DFS — if you find p in the left subtree and q in the right subtree, current node is LCA. Key problems: LCA of Binary Tree (LC 236), LCA of BST (LC 235), Kth Ancestor of a Node (LC 1483).