Depth-first search visits a node, then the whole subtree of its first child, then the next child, and so on. For the DOM, pre-order DFS is tree order: the order querySelectorAll returns. The recursive version is three lines. The iterative one pushes children onto a stack right to left so the leftmost comes off first, which avoids the call-stack limit on deep trees and makes it easy to skip a subtree or stop early. A generator that yields enter and exit events gives pre-order and post-order from one walk and stops lazily. Say the complexity: O(n) time and O(depth) extra space.
DFS on HTML nodes.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Visit the node, then recurse into each child in order, passing the depth down. Element children gives element nodes only. Use childNodes if text and comment nodes matter too. This is the answer to give first, before any refinements.
// Depth-first, pre-order: visit a node, then each child's whole subtree, left to right.// This is the DOM's "tree order": the order querySelectorAll returns.function dfs(node, visit, depth = 0) {visit(node, depth);for (const child of node.children) dfs(child, visit, depth + 1);}
passes 3 checks run on every build, against the native method where there is one
- visits in tree order
- reports each node's depth
- a single node
A stack replaces the call stack. Because a stack is last in, first out, children are pushed from last to first so the walk still goes left to right. The first check compares the order with the recursive walk on 100 random trees. Letting visit return 'skip' or 'stop' is how you prune hidden subtrees or end a search early. Recursion would need an exception or a flag threaded through every call.
// The same order with an explicit stack: no call-stack limit on deep trees.// visit may return 'skip' (don't go into this node's children) or 'stop' (end the walk).function dfs(root, visit) {const stack = [[root, 0]];while (stack.length) {const [node, depth] = stack.pop();const signal = visit(node, depth);if (signal === 'stop') return node;if (signal === 'skip') continue;// Push children right to left so the leftmost is popped first.for (let i = node.children.length - 1; i >= 0; i--) stack.push([node.children[i], depth + 1]);}return null;}
passes 4 checks run on every build, against the native method where there is one
- same order as the recursive walk, on 100 random trees
- 'skip' leaves out a subtree
- 'stop' ends the walk and returns the node
- a 100,000-deep tree doesn't overflow
A generator keeps, for each open node, the index of the next child to visit. It yields enter when it goes down and exit when it comes back up. Enter events are pre-order and exit events are post-order, which is what you need for an outline, closing tags, or computing subtree sizes bottom-up. Since nothing runs until the consumer asks, find stops after the first match. A check counts how many nodes were read to prove it. In the browser, document.createTreeWalker gives the same lazy pre-order walk.
// A lazy walk that reports both entering and leaving each node. Pre-order is the 'enter'// events, post-order the 'exit' events. Because it's a generator, a for...of that breaks// early never touches the rest of the tree.function* walk(root) {const stack = [{ node: root, depth: 0, next: 0 }];yield { type: 'enter', node: root, depth: 0 };while (stack.length) {const top = stack[stack.length - 1];if (top.next < top.node.children.length) {const child = top.node.children[top.next++];stack.push({ node: child, depth: top.depth + 1, next: 0 });yield { type: 'enter', node: child, depth: top.depth + 1 };} else {stack.pop();yield { type: 'exit', node: top.node, depth: top.depth };}}}// Uses: the first match (stops early), and an indented outline built from enter/exit.function find(root, test) {for (const { type, node } of walk(root)) if (type === 'enter' && test(node)) return node;return null;}function outline(root) {const lines = [];for (const { type, node, depth } of walk(root)) {if (type === 'enter') lines.push(' '.repeat(depth) + '<' + node.tag + '>');else if (node.children.length) lines.push(' '.repeat(depth) + '</' + node.tag + '>');}return lines.join('\n');}
passes 4 checks run on every build, against the native method where there is one
- enter events are pre-order; exit events are post-order
- find stops without walking the rest
- outline from enter and exit
- depths match
TreeWalker and NodeIterator
The DOM ships lazy depth-first walkers with filters (NodeFilter.SHOW_TEXT, a custom acceptNode that can reject or skip subtrees), the same skip/stop idea as the intermediate stage.
Accessibility checkers
Tools like axe walk the DOM depth-first to compute things like accessible names and heading order, skipping hidden subtrees.
Tree order defines a lot
Tab order without tabindex, querySelectorAll results and compareDocumentPosition all follow tree order, which is this pre-order DFS.
Pushing children left to right onto a stack, which visits them in reverse.
Recursing on deep or untrusted trees (generated markup can nest thousands of levels).
Using
childNodeswhen only elements were wanted, orchildrenwhen text matters.Mutating the tree (removing nodes) while walking a live
childrencollection.
When would you use BFS instead?
When you want the nearest match by depth (the shallowest heading, the closest descendant). BFS uses a queue and O(width) memory.
How do you walk without any extra memory?
Use parent and sibling pointers: go to firstElementChild if it exists, else nextElementSibling, else climb parentElement until a sibling exists. That's how TreeWalker can work in O(1) extra space.
How would you find the path to a node?
Keep the stack of open nodes (the generator already has it): at the target, the stack is the path from the root.