Recursive Algorithms on Trees and Lists

IB Computer Science · Abstract Data Structures (HL)

Why trees and recursion belong together. A binary tree is defined recursively: it is either empty, or a node with a left subtree and a right subtree, each of which is itself a binary tree. Any algorithm on a tree therefore has the same shape as the definition. Handle the empty case (the base case), then do something with the node and call yourself on the two subtrees. Iteration can do the same work only by managing its own stack of nodes still to visit, which is longer and more error-prone; recursion lets the call stack do that bookkeeping for free.

The template and its variations. HEIGHT(NODE): if NODE is null return 0; otherwise return 1 + the larger of HEIGHT(left) and HEIGHT(right). Almost every tree question changes only the last line. COUNT: 1 + COUNT(left) + COUNT(right). SUM: value + SUM(left) + SUM(right). LEAVES: return 0 for null, 1 when both children are null, otherwise LEAVES(left) + LEAVES(right). Searching a binary search tree is the one case that visits only one subtree: compare the target with the node's value, and recurse left if smaller, right if larger, stopping on a match or on null. The three traversals — pre-order, in-order, post-order — are the same recursion with the visit placed before, between or after the two recursive calls, and in-order on a binary search tree outputs values in sorted order.

Order of execution and the call stack. Recursive calls go down to the leaves first; values come back up afterwards, and a parent cannot return until both children have. The call stack is as deep as the tree is high: a balanced tree of 1 000 nodes is about 10 levels deep, a degenerate tree (values inserted in sorted order) is 1 000 deep, and a tree deep enough overflows the stack — which is why the same recursive sum that is elegant on a balanced tree can crash on a sorted-input tree. Recursion on a linked list has the same shape: the base case is the null pointer, and each call handles one node then recurses on the rest; but because a list of N items gives N nested calls, a loop is usually preferred for lists and recursion is reserved for trees.

Tracing recursion in the exam. Write each call on its own line with its argument, indent nested calls, and write the returned value beside the call once it is known. Never trace only the final answer: marks are for showing the base cases returning and the values combining on the way up. Two errors account for most lost marks: forgetting the base case (the function calls itself forever) and combining the results wrongly (adding heights instead of taking the maximum).

RECURSION ON TREES: ASK BOTH CHILDREN, TAKE THE MAX, ADD ONE 50 30 70 20 40 80 10 h = 1 + max(3, 2) = 4 h = 3 h = 2 h = 2 h = 1 h = 1 h = 1 an empty node (null) returns 0 — that is the stopping condition HEIGHT(NODE) if NODE = null then return 0 L = HEIGHT(NODE.left) R = HEIGHT(NODE.right) return 1 + max(L, R) the same template for every tree problem count nodes: return 1 + COUNT(L) + COUNT(R) sum of values: return NODE.value + SUM(L) + SUM(R) search in a BST: compare with NODE.value, go down one branch count leaves: null → 0; both children null → 1; else L + R forget the stopping condition = keep calling until the stack overflows ORDER OF EXECUTION: call down to the leaves FIRST, return values travel back up AFTER call stack depth equals the tree height: a balanced tree of 1,000 nodes is ~10 deep · a degenerate tree of 1,000 nodes is 1,000 deep recursion is natural for trees because each child is a smaller tree of the same form — a loop would need to manage a stack by hand
The figure on the left is a seven-node binary search tree with root 50, and beside each node is the height that the recursive function computes for the subtree at that node. How to read it: leaf 10 has height 1 because its two children are empty and empty returns 0; node 20 has height 1 plus the max of 1 and 0, which is 2; node 30 has 1 plus the max of 2 and 1, which is 3; and root 50 has 1 plus the max of 3 and 2, which is 4. The box on the right is the four-line HEIGHT function: if the node is empty return 0 — this is the stopping condition — otherwise ask for the height of the left child, ask for the height of the right child, and return 1 plus the larger value. The lower part of the box points out that almost every tree problem uses exactly this template and only the last line changes: counting nodes is 1 plus both sides, sum of values is the node value plus both sides, search in a binary search tree is comparing with the node value and then going down only one branch, counting leaves is returning 1 when both children are empty. The bottom box reminds us of the order of execution: the calls go down to the leaves first, then the return values travel back up; the call stack is as deep as the tree height, so a balanced tree of 1,000 nodes is only about 10 deep while a degenerate tree is 1,000 deep. Recursion is natural for trees because each child is a smaller tree of the same form; doing it with a loop requires managing a stack by hand.

Worked example: Example 1 — writing and tracing a recursive function that counts the leaves of a tree

For the tree in the figure (root 50; 30 and 70 are its children; 20, 40 are children of 30; 80 is the right child of 70; 10 is the left child of 20), write a function LEAVES(NODE) that returns the number of leaves, trace it fully, and explain why you cannot write return LEAVES(left) + LEAVES(right) + 1.

Solution

The function. if NODE = null then return 0; if NODE.left = null and NODE.right = null then return 1; return LEAVES(NODE.left) + LEAVES(NODE.right). Two stopping conditions: empty gives 0 because it is not a node, a leaf gives 1 because it is itself the thing to be counted; an internal node must not add 1 because it is not a leaf.

Trace. LEAVES(50) = LEAVES(30) + LEAVES(70).
  LEAVES(30) = LEAVES(20) + LEAVES(40).
    LEAVES(20) = LEAVES(10) + LEAVES(null); LEAVES(10) is a leaf → 1; LEAVES(null) → 0; so LEAVES(20) = 1.
    LEAVES(40) is a leaf → 1.
  so LEAVES(30) = 1 + 1 = 2.
  LEAVES(70) = LEAVES(null) + LEAVES(80) = 0 + 1 = 1.
LEAVES(50) = 2 + 1 = 3. The three leaves are 10, 40, 80 — a visual check agrees.

Why not add 1 at every node. return LEAVES(left) + LEAVES(right) + 1 counts every non-empty node, which is exactly COUNT, and gives 7 instead of 3. The difference between counting nodes and counting leaves lies entirely in where the 1 is added: at every node or only at a node with no children. This is the clearest example of only the last line changing in the tree recursion template, and it is also the question examiners use to tell those who understand from those who memorize.

Worked example: Example 2 — the same function, two trees: why insertion order decides the stack depth

The function SUM(NODE) = if null then 0 else value + SUM(left) + SUM(right). Run on two binary search trees both containing the numbers 1 to 1,000: tree A inserted in random order, tree B inserted in the order 1, 2, 3, ... Compare the number of calls, the maximum stack depth, and the risk, then state how to remedy it.

Solution

Number of calls — equal. The function visits every node exactly once and makes one extra call for each empty child, so both trees have 1,000 calls for nodes plus 1,001 calls for empty children — the same total, and the same result of 500,500. The amount of computation is O(n) on both.

Stack depth — very different. Tree A, inserted randomly, has a height of about log₂ of 1,000, that is, roughly 10 to 20 levels, so the call stack is never deeper than 20 frames. Tree B, inserted in ascending order: each new value is greater than all the old ones so it always becomes the right child, and the tree is a straight chain of 1,000 nodes — height 1,000. SUM(1) calls SUM(2) calls SUM(3) ... up to SUM(1000) before any call returns, so the stack is 1,000 frames deep at once.

Risk. With 1,000 elements it may still run, but with 100,000 elements inserted in order, the stack overflows and the program crashes on tree B while tree A is still only about 20 deep. The same correct function, the same data, a different outcome only because of insertion order — and sorted data is very common in practice (ascending codes, timestamps).

Remedy. Do not fix the function, fix the tree: use a self-balancing tree so the height is always O(log n) regardless of insertion order, or shuffle the data before inserting if you know it is sorted. The last option is to rewrite it with a loop and a self-managed stack in dynamic memory, where the limit is much larger than the call stack. A good evaluation distinguishes a correct algorithm from an algorithm that is safe on real data.

Common mistake

Trap 1 — adding the heights of the two children instead of taking the max. Height is the longest path down to a leaf, not a sum.
Trap 2 — a trace that writes only the final answer. The marks are in showing the stopping condition returning and the combined value on the way up.
Trap 3 — assuming a correct recursive function is safe. A tree degenerated by sorted data makes the stack as deep as n and overflow.

Key takeaway

Lesson 3 wrap-up. Four things to take into the exam room. One, the tree recursion template: empty returns the base value, then combine the node with its two children. Two, only the last line changes between height, node count, sum and leaf count. Three, down to the leaves first, return up afterwards, with the stack as deep as the height. Four, insertion order decides the height, so a balanced tree is the protection for recursion.

← Binary Trees, Traversals and Choosing a Structure · All IB Computer Science lessons · Practice IB Computer Science questions (free, instant scoring) · Applications of Stacks and Queues: Call Stacks, Undo, Buffers and Breadth-First Traversal →