Recursion, trees and heaps · core
Trees and the DOM in JavaScript
A tree is visited depth-first (pre-, in- or post-order, with recursion or a stack) or breadth-first level by level with a queue. The DOM is such a tree (children, parentNode, contains()), which is why frontend rounds favour tree questions.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- DFS pre-order (node, then children) for copying or serialising; post-order (children, then node) for heights, sizes and 'combine results'; in-order on a BST gives sorted order.
- BFS with a queue gives level order; process one level at a time with
for (let n = queue.length; n > 0; n--)(or a head index). - Height/depth: 1 + max(child depths). Counting, summing, finding a path are all small DFS functions.
- Lowest common ancestor (binary tree): post-order; return the node if it matches; the first node where both sides return non-null is the LCA. With parent pointers (DOM), walk up and check contains().
- Iterative DFS with an explicit stack avoids recursion limits on very deep trees.
- n-ary trees (DOM, file trees, org charts) use the same ideas with a children array; Employee Importance is DFS over an id → node Map.
The red pen
Common traps: mistake → fix
Mistake: BFS by recursion
Fix: recursion is depth-first; BFS needs a queue.
Mistake: BST rules apply to any binary tree
Fix: LCA by value comparison works only on a BST.
Mistake: Assume both nodes exist in LCA
Fix: ask; otherwise check both were found.
Easy to hard
Questions interviewers ask, easy to hard
- Maximum depth of a binary tree.
- Level-order traversal returning one array per level.
- In-order traversal without recursion.
- Lowest common ancestor in a binary tree; then in the DOM with parent pointers.
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.