-1

I need little help with this simple problem. I recieved a compiler error, but I don't know how to remove this error. Showing error in this line int n = totalTree(num);,
here is my code:

public class TotalNumberOfBinaryTrees {

    //static int elementCount = 50;

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int test =sc.nextInt();
        while(test>0){
            int num = sc.nextInt();
            int n = totalTree(num);
            System.out.println("totalTree"+n);
            test--;
        }
    }

    public int totalTree(int n) {
    if (n == 1 || n == 0)
            return 1;
    else {
            int left = 0;
            int right = 0;
            int sum = 0;
            for (int k = 1; k <= n; k++) {
        left = totalTree(k - 1);
        right = totalTree(n - k);
        sum = sum + (left * right);
            }
    return sum;
        }
    }
}
Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Saket Mittal
  • 3,466
  • 3
  • 26
  • 48

2 Answers2

1

totalTree is a non-static method. You can't call it from a static method (main) without creating an instance of your class.

I'm not sure if it makes any sense, but you can call it with :

int n = new TotalNumberOfBinaryTrees().totalTree(num);

or change it to a static method.

Eran
  • 374,785
  • 51
  • 663
  • 734
1

You cannot access non-static method from a static method, so declare the method as:

public static int totalTree(int n) {}  

Now the following code will have no compilation issues:

public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int test =sc.nextInt();
        while(test>0){
            int num = sc.nextInt();
            int n = totalTree(num);
            System.out.println("totalTree"+n);
            test--;
        }
    }

    public static int totalTree(int n) {
        if (n == 1 || n == 0)
            return 1;
        else {
            int left = 0;
            int right = 0;
            int sum = 0;
            for (int k = 1; k <= n; k++) {
                left = totalTree(k - 1);
                right = totalTree(n - k);
                sum = sum + (left * right);
            }
            return sum;
        }
    }
akhil_mittal
  • 21,313
  • 7
  • 90
  • 91