Hi, I'm trying to complete this method for a binary search tree and recursion has never been my strong point. All it does is return the total number of nodes in the tree. I have an answer that finds it a different way, but I wanted trying to get it to work this way, if it's even possible. The method so far doesn't return the right number of nodes and I'm not sure why

public int numNodes() {
    return numNodesHelper(root);
  }

  public int numNodesHelper(Node currNode) {
    int numNodes = 0;
    if (currNode == null) {
      return 0;
    }

      if (currNode.left == null && currNode.right == null) {
        return 1;
      }

      if (currNode.left != null)
        numNodes += numNodesHelper(currNode.left);
      if (currNode.right != null)
        numNodes += numNodesHelper(currNode.right);

      return numNodes;
    }
Re: Binary Search Tree- finding total number of nodes 80 80
public int callSize(){
        return Size(root);
    }
    public int Size(node n){
        if(n==null)
            return 0;
        else
            return 1+Size(n.left)+Size(n.right);
    }
Re: Binary Search Tree- finding total number of nodes 80 80

This forum is not to give out solution but rather teach those who ask...

PS: You should also follow the Java naming convension. The Size should be named as size because it is a method, not a class name.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.