Walk a menu tree breadth-first and depth-first
A navigation menu, a comment thread or a file tree can be walked two ways. Breadth-first visits everything on one level before descending, which is what you want when rendering a menu level by level or finding the nearest match. Depth-first follows one branch to the bottom first, which is what you want when flattening for display.
Implement two functions over the same node shape { id, children }, where children is an array of nodes and may be missing. Both take roots, an array of top-level nodes, and both return an array of id values; both return [] for an empty array of roots.
breadthFirst(roots) returns ids level by level: every root in array order first, then every child of those roots in the same order their parents were visited, then every grandchild, and so on. depthFirst(roots) returns ids in pre-order: each node immediately before its own descendants, with siblings in array order.
Arguments
rootsArray<{ id: unknown; children?: Node[] }>- The top-level nodes. Each may have a
childrenarray.
Returns
unknown[] — An array of id values in traversal order (level-by-level for breadthFirst, pre-order for depthFirst).
Examples
const tree = [
{ id: "file", children: [{ id: "new" }, { id: "open" }] },
{ id: "edit", children: [{ id: "undo" }] },
];
breadthFirst(tree);
// ["file", "edit", "new", "open", "undo"]All roots first, then all children, then all grandchildren.
const tree = [
{ id: "file", children: [{ id: "new" }, { id: "open" }] },
{ id: "edit", children: [{ id: "undo" }] },
];
depthFirst(tree);
// ["file", "new", "open", "edit", "undo"]Each branch is drained to the bottom before the next sibling starts.
What it has to do
breadthFirstvisits all nodes at one level before any node at the next.depthFirstvisits a node immediately before its descendants.- Both keep siblings in their array order.
- Both return an empty array when given no roots.
- Both treat a missing
childrenproperty as no children.
Notes
- Both run in O(n) time over n nodes. BFS uses O(w) space for a queue (w = widest level); DFS uses O(h) stack space (h = deepest branch).
- Reach for BFS when you want the nearest match from the root — the first match it finds is at the smallest depth.
- DFS is what you want when flattening for a virtualised list, since the natural recursion already produces pre-order.
Stuck? The javascript course covers everything this challenge needs.
- 1.breadth-first visits a menu level by level
- 2.depth-first follows each branch to the bottom
- 3.both return an empty array for no roots
- 4.both treat a missing children property as a leaf
- 5.the two orders differ on the same tree
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.