I\'m supposed to print a recursive Fibonacci tree, I\'ve gotten the recursive fi
ID: 3662606 • Letter: I
Question
I'm supposed to print a recursive Fibonacci tree, I've gotten the recursive fibonacci serise down pat, but I don't understand how to format how it prints. Here's my code:
public class Fibonacci {
public static void main(String[] args){
for (int i = 1; i <= 5; i++) {
System.out.println("fibonacci (" + i + ") = " + fib(i)); // display fibonacci number for each recursion until 20
}
}
public static long fib(long n){
if (n == 0 || n == 1){
return n; // returns n if n is a base case
}
else{
return fib(n-1) + fib(n-2); //recursive
}
}
}
And how it is supposed to be formatted:
fib(1)-->1
fib(2)
fib(0)-->0
fib(3)
fib(1)-->1
fib(4)
fib(1)-->1
fib(2)
fib(0)-->0
fib(5)
fib(1)-->1
fib(2)
fib(0)-->0
fib(3)
fib(1)-->1
Explanation / Answer
public class Fibonacci {
public static void main(String[] args){
for (int i = 1; i <= 5; i++) {
System.out.println(" finding fibbonocci("+i+")");
System.out.println("fibonacci (" + i + ") = " + fib_rec_print(i)); // display fibonacci number for each recursion until 20
}
}
public static long fib(long n){
if (n == 0 || n == 1){
return n; // returns n if n is a base case
}
else{
return fib(n-1) + fib(n-2); //recursive
}
}
public static long fib_rec_print(long n)
{
return fib1(n,0);
}
private static long fib1(long n, int d)
{
if(n==0 || n==1)
{
return n;
}
long f1=fib1(n-1,d+1);//call the fibonacci(n-1) with depth = d+1
for(int i=0;i<d;i++)
System.out.print(" ");//to represent the depth of the tree
System.out.println("fib("+(n-1)+")->"+f1);//printing the fibonocci value of f(n-1)
long f2=fib1(n-2,d+1);//call the fibonacci(n-1) with depth = d+1
for(int i=0;i<d;i++)
System.out.print(" ");//to represent the depth of the tree
System.out.println("fib("+(n-2)+")->"+f2);//printing the fibonocci value of f(n-2)
return f1+f2;
}
}
output: