AniUI Academy

Walk a menu tree breadth-first and depth-first

mediumData Structures+250 XPPractice

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 children array.

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

  • breadthFirst visits all nodes at one level before any node at the next.
  • depthFirst visits 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 children property 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.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.