Each subpattern solves a specific type of problem. Click on a card to view its template.
Template for: DFS — Recursive Traversal
Return immediately when node is nullptr — this is the natural recursion terminator.
Call the same function on node->left and node->right. Trust the recursion — assume they return the correct answer for their subtrees.
Use the results from the left and right subtrees to compute the answer for the current node and return it upward.
1// DFS skeleton — adapt order as needed2void dfs(TreeNode* node)3{4 if (!node) return; // base case56 // PRE-ORDER: process node BEFORE children7 process(node);89 dfs(node->left);10 dfs(node->right);1112 // POST-ORDER: process node AFTER children13 // process(node);14}1516// ── returning a value (e.g. height) ─────────────17int height(TreeNode* node)18{19 if (!node) return 0;2021 int leftH = height(node->left);22 int rightH = height(node->right);2324 return 1 + max(leftH, rightH); // combine25}
Sharpen your skills with hand-picked problems.
LeetCode #104
LeetCode #226
LeetCode #543
LeetCode #112
LeetCode #110
LeetCode #101
LeetCode #102
LeetCode #199
LeetCode #637
LeetCode #103
LeetCode #662
LeetCode #98
LeetCode #230
LeetCode #235
LeetCode #450
LeetCode #236
LeetCode #1123
LeetCode #1026
LeetCode #105
LeetCode #297
LeetCode #108
LeetCode #114
LeetCode #124
LeetCode #437
LeetCode #129
LeetCode #337
LeetCode #94
LeetCode #144
LeetCode #99