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).
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.