Sikau

Data structures · Day 9 · about 35 min

Recursion and trees

Hierarchies, depth-first walks and recursive thinking.

Things inside things

Folders contain folders, menus contain sections, the DOM contains elements: that's a tree — a root with children, which have children… Trees are naturally recursive: a tree is a node plus smaller trees, so functions on trees usually call themselves on each child.

Walking a tree

const menu = {
  name: "Menu",
  children: [
    { name: "Starters", children: [{ name: "Momo", price: 180 }, { name: "Chilli", price: 260 }] },
    { name: "Mains", children: [
      { name: "Thukpa", price: 220 },
      { name: "Thali", children: [{ name: "Veg thali", price: 300 }, { name: "Chicken thali", price: 380 }] },
    ] },
    { name: "Tea", price: 50 },
  ],
};

function print(node, depth = 0) {
  console.log("  ".repeat(depth) + node.name + (node.price ? ` (${node.price})` : ""));
  for (const child of node.children ?? []) print(child, depth + 1);
}
print(menu);

function countDishes(node) {
  if (!node.children) return 1;
  return node.children.reduce((sum, c) => sum + countDishes(c), 0);
}
console.log("dishes:", countDishes(menu));

function height(node) {
  if (!node.children) return 0;
  return 1 + Math.max(...node.children.map(height));
}
console.log("height:", height(menu));

Every recursive function needs a base case and must move towards it — otherwise: stack overflow.

The rest of this lesson

  • Thinking recursivelyexplain
  • Depth-first and breadth-firstexplain
  • Visit orderpredict
  • Tree vocabularymatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of Data structures