Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Flatten a tree with a recursive generator in JavaScript

10 Flatten a tree with recursion and yield*

hard

Walk a nested organisation tree depth-first with a recursive generator, carrying the depth along. Then write a breadth-first walk with an explicit queue and show that the two orders differ. Read only the first two nodes of the tree to prove the walk is lazy.

Stuck? Three hints, smallest first
  1. 1. yield the node, then yield* walk(child, depth + 1) for each child.
  2. 2. Breadth-first cannot be written with recursion the same way: it needs a queue you shift from.
  3. 3. Drive next() twice instead of spreading, and the rest of the tree is never visited.

The answer

const org = {
  name: 'Lagos HQ',
  staff: 12,
  units: [
    { name: 'Ikeja branch', staff: 5, units: [{ name: 'Ikeja counter', staff: 2, units: [] }] },
    { name: 'Yaba branch', staff: 3, units: [] },
  ],
};

function* walk(node, depth = 0) {
  yield { name: node.name, staff: node.staff, depth };
  for (const child of node.units ?? []) yield* walk(child, depth + 1);
}

function* levels(root) {
  const queue = [root];
  while (queue.length) {
    const node = queue.shift();
    yield node.name;
    queue.push(...(node.units ?? []));
  }
}

const flat = [...walk(org)];
let total = 0;
for (const node of walk(org)) total += node.staff;

const lazily = walk(org);
const firstTwo = [lazily.next().value.name, lazily.next().value.name];

let chain = { name: 'n0', staff: 0, units: [] };
for (let i = 1; i <= 200; i++) chain = { name: 'n' + i, staff: 0, units: [chain] };
const deepWalk = [...walk(chain)];

console.log('depth-first  :', flat.map((n) => `${'  '.repeat(n.depth)}${n.name}`).join(' | '));
console.log('breadth-first:', [...levels(org)]);
console.log('staff total  :', total);
console.log('read two, stopped:', firstTwo);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('depth-first, pre-order', flat.map((n) => n.name), ['Lagos HQ', 'Ikeja branch', 'Ikeja counter', 'Yaba branch']);
test('the depth comes along with each node', flat.map((n) => n.depth), [0, 1, 2, 1]);
test('breadth-first visits siblings before children', [...levels(org)], ['Lagos HQ', 'Ikeja branch', 'Yaba branch', 'Ikeja counter']);
test('the whole tree totals 22 staff', total, 22);
test('a leaf walks to just itself', [...walk({ name: 'Kiosk', staff: 1, units: [] })].length, 1);
test('a missing units array is fine', [...walk({ name: 'Solo', staff: 1 })].map((n) => n.name), ['Solo']);
test('reading lazily costs only what you read', firstTwo, ['Lagos HQ', 'Ikeja branch']);
test('200 levels of nesting still walks, deepest last', [deepWalk.length, deepWalk.at(-1).depth], [201, 200]);

Recursion plus yield* is the shortest correct tree walk in the language, and it reads like the definition of the tree: a node, then its subtrees. Compare it with the accumulator version — const out = []; visit(node, out); — which needs the array threaded through every call and returns nothing usable until the whole tree is walked.

Depth-first is naturally recursive because the call stack is the stack you need. Breadth-first is not: a queue you shift from cannot be expressed as recursion without carrying the queue explicitly, so levels stays a loop. That asymmetry, not the output order, is the reason the two look so different.

The 200-level assertion is a limit worth knowing. Each level of yield* adds a frame, and every value yielded from the bottom is relayed up through all of them, so a walk of a tree of depth d costs O(d) per value. Fine for filesystems and org charts, wrong for a linked list of 100,000 nodes — flatten that with an explicit stack instead.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.