Solve a Smaller Version First

Recursion means a function calls itself on a shrunken copy of its task. Every recursive function needs two parts: a base case small enough to answer directly, and a step that shrinks the problem and combines the smaller answer with a bit of its own work. Trees are recursive by nature, because every child of a node is the root of a smaller tree, so it pays to get comfortable with recursion before you start on them.

The Smaller Version of a List

A linked list is recursive too. A list is either empty, or it’s one node followed by a shorter list. That definition turns straight into code:

Language: JavaScript
function countNodes(node) {
  if (node === null) return 0;
  return 1 + countNodes(node.next);
}

const ship = { title: "Ship", next: null };
const tasks = { title: "Draft", next: { title: "Review", next: ship } };
console.log(countNodes(tasks));

The empty list is the base case, and every other call counts one node and leaves the rest of the list to a smaller call:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.