0

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;
    }
3
Contributors
2
Replies
7
Views
4 Years
Discussion Span
Last Post by Taywin
0
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);
    }
0

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.

Edited by Taywin

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.