Recursive Tree
A recursive tree, in the context of recursion, is a visual representation of how recursive function calls are stacked on top of each other. It's essentially a tree-like structure where each node represents a function call, and child nodes represent subsequent function calls made within that function.
Let's take an example of a simple recursive function to calculate the factorial of a number:
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int result = factorial(5);
cout << "Factorial of 5 is: " << result << endl;
return 0;
}
When factorial(5)
is called, a sequence of function calls is made:
factorial(5)
↓
5 * factorial(4)
↓
4 * factorial(3)
↓
3 * factorial(2)
↓
2 * factorial(1)
↓
1
This sequence of function calls forms a tree-like structure, where each function call is a node, and each subsequent function call is a child node. This structure is called a recursive tree.