2. Recursive Functions • Recursive functions are functions that call themselves. •
Data structures, especially linked implementations of binary trees, sometimes
use recursive functions
Example: Factorial Function • The factorial function is often written as a
recursive function. • The factorial of a positive integer is the product of all
positive integers less than or equal to the number. 5 factorial is written 5! 5! =
5 * 4 * 3 * 2 * 1 = 120 3! = 3 * 2 * 1 = 6 0! is defined to be
3. Recursive Process (cont.)
x = factorial( 4 );
int factorial( int num )
{ if ( num == 0 || num == 1 ) 4 replaces each
occurrence of num Recursive Process
return 1;
return num * factorial( num – 1 );
}
4. Base Case
1 int factorial( int num )
2 {
3 if ( num == 0 || num == 1 )
4 return 1;
5 return num * factorial( num – 1 );
6 }
Notice that these lines stopped the recursion – without these
lines, the function will call itself over and over again (infinite
recursion
5. Infinite Recursion
1 int factorial( int num )
2 {
3 if ( num == 0 || num == 1 )
4 return 1;
5 return num * factorial( num – 1 );
6 }
If one makes a mistake and inputs a negative number into
this function: factorial( -2 ); what will happen? Infinite
recursion
6. Guidelines
• There must be a base case that stops recursion.
• Each recursive call should approach the base case.
• The recursive function call should work for the base case.
• The recursive function call should work for the case next to the base
case.
• The recursive function should make logical sense, assuming that the
recursive function call inside it does everything it should do
7. Recursion on a Linked List (cont.)
bool search( Node *ptr, T& foundItem, T& target)
{
.if ( ptr == NULL ) return false;
if ( ptr->info == target )
{
foundItem = ptr->info; return true;
}
return search( ptr->next, foundItem, target );
}
Searching for a Mercedes in the linked list: Car mercedes, foundCar;
… bool found = search( start, foundCar, mercedes );