Skip to the code
cf.
+10 XP

#700 Element IDs in Page Order

easy

An accessibility audit tool walks a page and reports elements in the order they appear in the HTML. The page is given as a tree of plain objects: each element has a tag, an id, and optionally children, a list of child elements in order.

Write pageOrder(root) that returns the id of every element in document order: an element comes before its children, and all of a child's descendants come before the next child. If root is null, return an empty array.

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: ["root","top","title","content","intro","list","a","b"]

Each element is listed before everything inside it, and header (with its h1) comes before main.

Example 2

Input: root = {"tag":"div","id":"only"}
Output: ["only"]

A single element with no children field.

Constraints

  • The tree has 0 to 10^4 elements and can be up to 10^4 levels deep.
  • Every id is a unique non-empty string.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

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