Recursive top-down and bottom-up traversals on hierarchical structures
351 problems·40 Easy·223 Medium·88 Hard
Pattern Study Guide & Cheat Sheet· O(N) visits each node once · O(H) call stack where H is tree height (O(log N) balanced, O(N) worst-case skewed)
▼
Traverse binary or general trees by recurring deep along branches, computing subtree metrics bottom-up (postorder) or passing state top-down (preorder).
Core Invariant: Recursive Trust: Assume `dfs(node.left)` and `dfs(node.right)` return the correct subtree answers. Combine them at `node` with the base case (`if not node: return base_val`).
Recognize it (Keywords & Signals)
Maximum / minimum depth of binary tree
Invert / clone binary tree
Diameter of binary tree
Lowest common ancestor (LCA)
Path sum / maximum path sum across branches
Check balanced binary tree
When NOT to use
Level-by-level processing or shortest path in terms of edge counts (Tree BFS is cleaner).
How to solve (Step-by-step)
1.Handle base case: `if not node: return 0` (or `None`, `True`).
2.Recursively solve left subtree: `left = dfs(node.left)`.
3.Recursively solve right subtree: `right = dfs(node.right)`.
4.Combine results at parent: e.g., update global variable `self.max_diameter = max(self.max_diameter, left + right)`.
Tree Depth-First Search (DFS) frequently asked questions
What is the Tree Depth-First Search (DFS) pattern in coding interviews?
Recursive top-down and bottom-up traversals on hierarchical structures It is categorized under Trees & Graphs and features 351 curated interview problems across Easy (40), Medium (223), and Hard (88) difficulties.
Which tech companies frequently test Tree Depth-First Search (DFS)?
Companies frequently asking Tree Depth-First Search (DFS) questions include Google, Amazon, Meta, Microsoft, Bloomberg, Uber.
How do I master the Tree Depth-First Search (DFS) pattern?
Start by studying the algorithmic strategy and template code, then practice Easy and Medium problems before attempting Hard problems under timed conditions.