Each subpattern solves a specific type of problem. Click on a card to view its template.
Pre / In / Post-order — choose the order based on when you need the parent vs children.
Use a queue to process the tree row by row — ideal for level-specific questions.
Exploit BST ordering: left < node < right to search, insert, and validate in O(H).
Post-order DFS: the LCA is the first node that finds both targets in different subtrees.
Rebuild a tree from traversal arrays or encode/decode it to a flat string.
Compute optimal values over all root-to-leaf or node-to-node paths with post-order DP.
Replace recursion with an explicit stack — required when recursion depth exceeds the call-stack limit.
Template for: DFS — Recursive Traversal
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}
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