Given two identical DOM trees and a node in one, find the matching node in the other.
MediumP3Coding
Two DOM trees have identical structure. Given the root of each tree and a node inside the first tree, return the node at the same position in the second tree.
Implement findMatchingNode(rootA, rootB, target).
- Nodes expose
parentNodeand achildrenlist, like DOM elements. targetcan berootAitself, in which case the answer isrootB.- If
targetis not insiderootA, returnnull. - Do not search by tag, id or text: elements may repeat. Use the position only.
Example 1
- Input
- rootA: div > [p, ul > [li, li]]; target = the second li of rootA
- Output
- the second li of rootB
- Why
- The path from the root is child 1 (ul), then child 1 (the second li).
Constraints
- The trees have the same shape.
- Depth up to 10^4, so avoid recursion that could overflow the stack.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 6. ⌘Enter runs, ⌘⇧Enter submits.