You are on page 1of 1

TREE RECURSION

Let’s say the value of n = 3;

fun(3)

def fun(n):

if(n > 0): // the value of n [3] is greater than zero (0), so it prints the value of as
seen in the next line of code
3
print(n)
2
fun(n – 1) //the value of n subtracts to 1, so it will get [2] a new value
fun(n)
1
fun(n – 1) //same as the previous code, the new value of n will be
subtracted to 1 which results to 1, as the new value of fun(n)

def fun(n)

if(n > 0): // the value of n [1] is greater than zero, so the next line of code will
print the value of n
1
print(n)
0
fun(n – 1) // the value of n [1] subtracts to 1 results to 0, then it will
terminate and proceed to fun(2)

fun(2)

def fun(n):

if(n > 0):


2
print(n)
1
fun(n – 1)
0
fun(n – 1) // proceeds to fun(1) since the program terminated as it
answers to 0

fun(1)

def fun(n)

if(n > 0):


1
print(n)
0
fun(n – 1) // the value of n [1] subtracts to 1 results to 0, then it will
terminate

Output:
 The output will be 3 2 1 1 2 1 1 as seen in the highlighted yellow text.
Whereas the highlighted purple is where the program terminated and proceed to another value of function.

You might also like