-2

I couldn't find an answer to this on the forums, sorry if this has been answered and I missed it.

I am drawing a blank here on using recursion on a non static method.

Example:

  public static void farLeft(BTNode root){
     if(root !=null)  
       return farLeft(root.left);
  }

This is just some random code I put in here. Now if I wanted to do that exact same thing using a non-static method, how would I use recursion on a non-static method? My book doesn't do a good job at explaining it.

snobbysteven
  • 29
  • 1
  • 5

3 Answers3

1

You are returning a non-void object in a method that is returning void. Other than that, you can just use a non-static method like this:

public BTNode farLeft(BTNode root){
    if(root !=null)
        return farLeft(root.left);

    //Return root because root has no left child
    return root;
}
Marv
  • 3,517
  • 2
  • 22
  • 47
0

For a non static method you will need to call it using the class instance. The method should not be private.

If the method is implemented in the class BTNode it would look something like this:

public BTNode farLeft(BTNode root){
     if(root !=null)  
         return root.farLeft(root.left);
}
Udy
  • 2,492
  • 4
  • 23
  • 33
0
public BTNode farLeft(BTNode root)
{
    BTNode farLeftChild = null;
    if(root !=null)
    {
        farLeftChild = farLeft(root.left);          
    } 

    return farLeftChild == null? root : farLeftChild;
}



Hope this helps. Good luck and have fun programming!

Cheers,

Lofty

Lofty
  • 96
  • 3