Skip to the code
+10 XP

#702 How Deep Is the Markup?

easy

Deeply nested markup slows down style calculation, so a linter warns when a component's tree is too deep.

Write maxDepth(root) that returns the number of elements on the longest path from root down to an element with no children. A single element has depth 1, and a null tree has depth 0. Elements have tag, id, and optional children.

Example 1

Input: root = {"tag":"body","id":"root","children":[{"tag":"header","id":"top","children":[{"tag":"h1","id":"title"}]},{"tag":"main","id":"content","children":[{"tag":"p","id":"intro"},{"tag":"ul","id":"list","children":[{"tag":"li","id":"a"},{"tag":"li","id":"b"}]}]}]}
Output: 4

body → main → ul → li is 4 elements long.

Example 2

Input: root = {"tag":"div","id":"x"}
Output: 1

One element alone has depth 1.

Constraints

  • The tree has 0 to 10^4 elements and can be up to 10^4 levels deep.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).