Amir Hasan Amir Hasan - 1 year ago 47
Java Question

In Java, when I pass an array to a recursive method, I get an error.

package test;


public class TreeOperations {
public static int minDepthBT(int[] a, int i )
if((i<1)|| (i<a.length))
return 0;
int x = minDepthBT(a[2*i],(2*i));
int y = minDepthBT(a[2*i+1],(2*i +1));
if(y==0) return y+1;
else if(x==0) return x+1;
return Math.min(x,y);

public static void main(String[] akjhk) throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(;
PrintWriter out = new PrintWriter(System.out,true);
int n = Integer.parseInt(br.readLine());
int a[] = new int[n];
String s[] = br.readLine().split(" ");
for(int i=0;i<n;i++)
a[i] = Integer.parseInt(s[i]);
int depth = minDepthBT(a,1);

In the above code the error is shown in two pics here one and two.

When I use an iterative method for example :

int Sum(int a[])
int sum =0;
for(int i=0;i<a,length;i++) sum += a[i];
return sum;

no error is received. What does happen in case of recursive methods?

Answer Source

Your problem is here:

int x = minDepthBT(a[2*i],(2*i));

for example.

Your method is declared to have two parameters: an array of int, and an int.

Here, you are calling the method ... using two int values.

Long story short: when calling your method recursively, then you have to provide exactly those parameters that are expected; in your case: you probably want to simply call with (a, 2*i).


Or, you would have to do something like:

int arrayForRecursiveCall[] = new int[whatever length];
... then you put some values in that array and then
minDepthBT(arrayForRecursiveCall, 2*i);

As said - the core thing is: you have to pass an array as first argument. A single int cant work!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download