Find the path to a node in a tree
Search a nested file tree or a category menu, land on a match, and now the UI has to expand every ancestor to reveal it and draw a breadcrumb. That means knowing the whole path, not just the node.
Implement findPath(root, targetId). root is a node shaped { id, children } where children is an array of nodes and may be missing. Return an array of id values leading from the root to the node whose id equals targetId, inclusive of both ends. When the root itself is the target, return an array holding just its id. When no node matches, return an empty array. When several nodes could match, return the path to the first one found by a depth-first pre-order walk with siblings in array order.
What it has to do
- Return the ids from the root down to the target, inclusive.
- Return an array with a single id when the root is the target.
- Return an empty array when nothing matches.
- Search branches in array order and stop at the first match.
- Treat a missing
childrenproperty as no children.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.