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.
Arguments
root{ id: unknown; children?: Node[] } | null- The root of the tree to search.
targetIdunknown- The
idof the node whose path is wanted.
Returns
unknown[] — The ids from the root to the matching node, inclusive, or [] when nothing matches.
Examples
const tree = { id: "root", children: [
{ id: "a", children: [{ id: "a1" }, { id: "a2", children: [{ id: "a2x" }] }] },
{ id: "b" },
]};
findPath(tree, "a2x");
// ["root", "a", "a2", "a2x"]findPath({ id: "root" }, "root");
// ["root"] — the root itself is a valid matchfindPath({ id: "root", children: [{ id: "a" }] }, "missing");
// [] — no matchWhat 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.
Notes
- Worst case O(n) time — the target could sit in the last branch — with O(h) stack space.
- The clean trick is letting the recursion return the empty array for 'miss' and a non-empty path for 'hit', so the caller just prepends its own id to any non-empty result.
Stuck? The javascript course covers everything this challenge needs.
- 1.builds the path to a deeply nested node
- 2.returns a single id when the root is the target
- 3.returns an empty array when nothing matches
- 4.finds a node in a later branch
- 5.handles a lone leaf node
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.