Problem Solving Fundamentals · Recursion

Count every folder

tree recursion

Count every folder

You have a folder holding other folders, and those hold more folders, deeper than you can see at a glance. You want a count of every folder in there, at every level. A loop over the top layer would stop after the first pass and miss the rest.

That is tree recursion. A folder is a node, and the folders inside it are its branches. The count of a tree is one for this folder plus the count of every branch below it. The task on the whole tree is the same task on each smaller tree nested inside.

Name the case that stops. A folder with no subfolders has nothing left to open, so its count is 1 — itself. That is the base case, and it answers without looking any further down.

Shrink the input by handing each child folder to the same function, so every branch is counted by a smaller run of itself. Then trust the call: assume countNodes(child) already returns the count of everything under that child, and add up what each branch reports, then add this node.

function countNodes(node) {
  if (node.children.length === 0) {
    return 1;
  }

  return 1 + node.children.reduce((total, child) => total + countNodes(child), 0);
}

One node plus the totals from its branches — that is the whole tree.

Export countNodes from index.js. It returns the number of folders in a folder tree, counting the root and every nested folder.

Challenge

A folder holds other folders, which hold more, as deep as you like. Export a countNodes function from index.js that counts every folder in the tree by recursing into each branch.

countNodes takes a node shaped like { name, children }, where children is an array of child nodes. It returns the total number of nodes: the root and every descendant at any depth. A node whose children array is empty counts as one.

index.js
export function countNodes(_node) {
  return 0;
}

export function render(mount) {
  const tree = {
    name: 'root',
    children: [
      { name: 'a', children: [] },
      { name: 'b', children: [{ name: 'c', children: [] }] },
    ],
  };

  mount.textContent = `countNodes(tree) = ${countNodes(tree)}`;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.