Tree Traversal Drill 12-Day
Reach for the right traversal — preorder, inorder, postorder, or BFS — within seconds of reading a tree problem, and write the base case before the recursive case.
By Alex Chen, Founder, InterviewChamp.AI · 12 problems · ~14h · difficulty: mixed · Last verified
The recursion warm-up. base = null returns 0, recurse = 1 + max(left, right). Every tree problem starts with this template.
Structural recursion on two trees in lockstep. Practice the 'both null', 'one null', 'values differ' base-case ladder out loud.
Swap and recurse. Famous because Max Howell flunked it at Google — don't be Max. Three lines of postorder work.
Same-tree variant: compare left.left to right.right, left.right to right.left. The mirror condition is the whole problem.
DFS carrying remaining target. Base case: leaf node with target == value. Drill the 'leaf only' condition — interior nodes don't count.
Backtracking on trees. Append to path on the way down, pop on the way up. The template that unlocks path-sum-ii and root-to-leaf problems.
The trick: recurse returns DEPTH, side-effect updates the diameter. First problem where 'recurse returns X but you want Y' bites.
BFS with a queue. Snapshot the queue size at the top of each level. The 'levels' framing transfers directly to graph BFS.
BST property = O(log n). Walk down: both values left? go left. Both right? go right. Otherwise current node IS the LCA.
Carry (lo, hi) bounds down the recursion. The 'compare each node to its parent' shortcut is the wrong answer — interviewers test for that exact slip.
Path-sum + backtracking output. The append/pop dance on the path list is the interview probe — narrate it as you write.
Capstone. Use a hash map for O(1) inorder lookups. The 'first preorder element is the current root' framing is the entire algorithm.
Ready to drill these live?
Get the AI copilot in your ear during real interviews. Real-time transcription. Streaming answers. Post-call scorecard.
Download the desktop app →