Example code
This example demonstrates how the Fibonacci function creates a branching recursion tree:How it works
The recursive Fibonacci function:- Base case: Returns
nwhenn <= 1 - Recursive case: Returns
fib(n-1) + fib(n-2), creating two branches at each level - Each call spawns two child calls until reaching the base case
This example demonstrates overlapping subproblems - notice how
fib(4), fib(3), fib(2), etc. are calculated multiple times in the recursion tree.Decorator configuration
The@vs decorator is configured with custom node styling:
shape="record": Uses a record-based node shapecolor="#f57542": Sets the border color to orangestyle="filled": Enables filled nodesfillcolor="grey": Sets the fill color to grey
Output
Running this code withfib(6) generates:
- Console output:
8(the 6th Fibonacci number) - Animation file:
fibonacci.gifshowing the complete recursion tree with a 2-second delay between frames