Skip to the solution
EasyFrontendAsked in 20245 min read

Document tree depth check

1.7k views

The problem

Problem, as an interviewer would state it: "Given a DOM node, compute the maximum depth of the element tree rooted at it — a leaf counts as depth 1."

Examples:

Code
<div id="root"><div><span>...</span><div><p>deep</p></div></div></div>
maxDepth(root) -> 4

Clarifying questions expected:

  • Does a leaf (no element children) count as depth 1 or depth 0?
  • Should text/comment nodes count toward depth at all, or only real element children?
  • Is the input guaranteed to be a genuine tree (no cycles), the way a real DOM always is?

Code / implementation expected: Yes — real, direct proof against a real jsdom tree with a known shape that the computed depth is correct at multiple points in the tree, not just at the root.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a recursive max-depth function correctly computes depth at multiple points in a real jsdom tree with a known shape

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 13 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Custom getElementById traverse

Continue