title: Counting the nodes in a binary search tree
body: <p>I need to create a recursive method that takes as a parameter the root node of a binary search tree. This recursive method will then return the int value of the total number of nodes in the entire binary search tree.</p>
  
  <p>This is what I have so far:</p>
  
  <pre><code>public class BinarySearchTree&lt;E&gt; extends AbstractSet&lt;E&gt;
  {
  protected Entry&lt;E&gt; root; 
  
  
  //called by the main method
  public int nodes()
  {
      return nodes(root);
  }       
  
  //nodes() will count and return the nodes in the binary search tree
  
  private int nodes(Entry&lt;E&gt; current)
  {    
      if(current.element != null)
      { 
          if(current.left == null &amp;&amp; current.right == null)
          {
              if(current.element == root.element)
              return 1;                   
  
              deleteEntry(current);              
              return 1 + nodes(current.parent);
          }
          else if(current.left != null &amp;&amp; current.right == null)        
              return nodes(current.left);
  
          else if(current.left == null &amp;&amp; current.right != null)
              return nodes(current.right);
  
          else if(current.left != null &amp;&amp; current.right != null)
              return nodes(current.left) + nodes(current.right);      
      } else return 1;
      return 0;
  }
  </code></pre>
  
  <p>The main method calls nodes like so:</p>
  
  <pre><code>        System.out.println ("\nThis section finds the number of nodes "
               + "in the tree"); 
  
          System.out.println ("The BST has " + bst.nodes() + " nodes");
  </code></pre>
  
  <p>So I was running the search by traveling in order, once I'd get to a node with no children I would delete the current node and return to the parent node and continue. I ran a debug of the method I have above and the program crashes with a NullPointerException() when it finally counts and removes all the nodes on the left and right side of the root node and tries to return 1.</p>
  
  <p>This is for my lab, the method MUST be recursive.</p>
  
  <p>I'm very lost at this point, does anyone know what I'm doing wrong?</p>