David Rumpf
David Rumpf

Reputation: 57

How to use a Method from a nested class inside the Body of a Method from the first layer class

I am Studying Systems-Engineering for just 2 Month so please go easy on me. I am working on a Project with lists, stacks and Binary Trees. The Code I am having trouble with is the one inside of the Binary Tree.

public class BinaryIntTree {


public static class Node {
    
    int value;
    
    The left child.

    Node leftChild;
    
    public int getNodeCount(Node node) {
        if(node == null) {return 0;}
        int counter = 0;
        
        if(node.leftChild == null && node.rightChild == null) {
            return 1;
        } else {
            counter += 1;
            if (node.leftChild != null) {
                counter += getNodeCount(node.leftChild);
            }
            if (node.rightChild != null) {
                counter += getNodeCount(node.rightChild);
            }
        }
        return counter;
    }
    
    
    public Node(int value) {
        this.value = value;
    }

 public int getNodeCount() {
    return root.getNodeCount(root);
}

the second getNodeCount() is in the Main class and I want, that if I use getNodeCount(), that I can't change the Object(root), which is used as the starting point. So I thought id just implement it in the nested Node class and let it be called in the Method from the Main class.

But it throws out a NullPointerException, which should be solved with if(node == null) {return 0;} but it does not. Thank you for your help in advance, also please no comment on the Method per se, since I want to solve the recursive method myself.

Upvotes: 1

Views: 37

Answers (1)

Mureinik
Mureinik

Reputation: 311418

getNodeCount takes a Node as an argument, and doesn't use the Node instance it's called upon (i.e., the this), meaning it should probably be static. Once you make it static, you can call it without an instance, and thus avoid the NullPointerException you're running into:

public int getNodeCount() {
    return Node.getNodeCount(root);
}

Upvotes: 1

Related Questions