Instructors and textbooks frequently use two common examples to introduce recursion. The text presents both examples as rules, functions, and C++ functions. A third bonus example illustrates elegant, recursive solutions for visiting or traversing the nodes in a binary tree.
The Factorial Function
The factorial function frequently appears in combinatorial and permutation problems. It is only defined on integers, but the gamma function (not covered here) extends the factorial function to real numbers.
Few number sequences can match the ubiquitousness of the Fibonacci numbers, which appear everywhere from architecture to biology (see Fibonacci Sequence at Math Is Fun). Can you see how the function implements the rule for forming the Fibonacci sequence?
A binary tree example. Each circle in the picture represents a node, an instance of the node structure. Each node has some data, represented by the letters "A" through "G," and two pointers named left and right, represented by the lines underneath each node. The top node, containing data "A," is called the root, and the nodes at the bottom, "D," "E," "F," and "G," are called leaves.
Binary trees are inherently recursive data structures - any node in the tree is the root of a sub-tree. So, the sub-tree whose root is "B" is also a tree and can be used with any tree operation.
We can conveniently place the structure specification and function prototype in a header file. Furthermore, we are deliberately vague about what we mean by Data and how the display operation works.
The structure specification and the function prototype are sufficient to write a set of small, simple, and quite elegant recursive functions that display the data in a binary tree.
Inorder
Preorder
Postorder
void visit(node* n)
{
if (n->left != nullptr)
visit(n->left);
display(n->d);
if (n->right != nullptr)
visit(n->right);
}
void visit(node* n)
{
display(n->d);
if (n->left != nullptr)
visit(n->left);
if (n->right != nullptr)
visit(n->right);
}
void visit(node* n)
{
if (n->left != nullptr)
visit(n->left);
if (n->right != nullptr)
visit(n->right);
display(n->d);
}
(a)
(b)
(c)
Recursive binary tree traversal functions. Accessing a tree node is called visiting the node. Formally, computer scientists call visiting all the tree nodes in a particular order traversing the tree, and informally, they call it walking the tree. There are three tree traversal orders: inorder, preorder, and postorder. By writing visit as a recursive function, we can select a traversal order by where we locate the call to display. Notice that the traversal functions have two recursive paths (highlighted). The visit order for each traversal is as follows: