FrontendPro

23Build a basic DOM traversal utility (DFS and BFS)

easyAbout 15 minutesCodingdomtreesbfsdfs

Problem

Implement two functions that walk the element tree under root (including root itself) and return the elements as an array:

  • dfs(root): depth-first, pre-order. A parent comes before its children, and a whole subtree is finished before its next sibling.
  • bfs(root): breadth-first. All elements at depth 1 come before any at depth 2, and so on, left to right.
// <section id="a">
//   <div id="b"><p id="d"></p><p id="e"></p></div>
//   <div id="c"><p id="f"></p></div>
// </section>
dfs(a).map((el) => el.id); // ["a", "b", "d", "e", "c", "f"]
bfs(a).map((el) => el.id); // ["a", "b", "c", "d", "e", "f"]

Requirements

  • Visit elements only; skip text and comment nodes.
  • Do not use recursion: both functions must work for a tree 20,000 levels deep.
  • Do not use querySelectorAll or TreeWalker.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

Push root. Then repeatedly pop an element, record it, and push its children. A stack is last in, first out, so the most recently found branch is explored first.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever