Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program to generate recursion tree for generic recursive program

Often when solving a recursive or dynamic programming problem, I find myself drawing a recursion tree to help simplify the question for me. However, for some questions which are complicated I have access to the solution but no idea how to draw the tree.

What I have tried so far is printing out the calling function and it's parameters, and this has proved helpful in some examples. However, I saw this tree for fibonacci(5) here generated by mathematica in this answer: https://mathematica.stackexchange.com/questions/116344/how-do-i-create-a-recursive-tree-plot-for-the-fibonacci-sequence

enter image description here

I was wondering if I could generate the same kind of tree in a mainstream high level language like Python, Java, or C++? The tree could just have the nodes as the function name and parameters like in the image.

like image 407
user3586940 Avatar asked Mar 13 '26 04:03

user3586940


1 Answers

I’ve made a simple python package called recursion-visualiser which you can install via pip that helps you to easily trace function calls for any arbitary recursive function and save tree as gif and png image by simply adding a decorator to your function.

Let's draw the tree for recursive Fibonacci function. Here is the recursive code:

def fib(n):
    if n <= 1:
        return n
    return fib(n=n - 1) + fib(n=n - 2)

def main():
    # Call function
    print(fib(n=6))

if __name__ == "__main__":
    main()

Now let's modify the code to draw recursion tree. First let's draw a very minimalist example

# Import Visualiser class from module visualiser
from visualiser.visualiser import Visualiser as vs

# Add decorator
@vs()
def fib(n):
    if n <= 1:
        return n
    return fib(n=n - 1) + fib(n=n-2)

def main():
    print(fib(n=6))
    vs.make_animation("fibonacci.gif", delay=2)

if __name__ == "__main__":
    main()

The output file is saved as fibonacci.gif and fibonacci.png. Here is how output animation looks: Animation.gif Also the final image of recursion tree: tree.png

We can also make it better using node color and other properties:

# Import Visualiser class from module visualiser
from visualiser.visualiser import Visualiser as vs

# Add decorator
@vs(node_properties_kwargs={"shape":"record", "color":"#f57542", "style":"filled", "fillcolor":"grey"})
def fib(n):
    if n <= 1:
        return n
    return fib(n=n - 1) + fib(n=n-2)

def main():
    print(fib(n=6))
    vs.make_animation("fibonacci.gif", delay=2)

if __name__ == "__main__":
    main()

Here is the output which looks much better: animation.gif

Here is the final image of the recursion tree: out.png

Check out more examples at here

like image 99
Bishal Sarang Avatar answered Mar 14 '26 20:03

Bishal Sarang