I'm currently doing an assignment in which I need to use a graph with connected vertices in an array.
I need to count each node in the graph, and have attempted to do it recursively.
public int getAmountOfNodes(Node node, int countFrom){
for (Node n : node.children) {
if (n != null) {
countFrom++;
getAmountOfNodes(n, countFrom);
}
}
return countFrom;
}
This is what I've attempted so far, but it's not quite working out the way I was hoping. I've attempted to debug the code, and it seems the counting works the way it's supposed to (counting each node that isn't null).
Problem seems to be that when the recursive stack ends, say that countFrom has hit 5, and the method returns 5, the next recursive call in the stack doesn't "remember this", and returns the amount it had counted up to before, say 4. This means that the final returned integer is only the amount that the first recursive call had counted to, that is, the amount of children the very first node has.
I've been trying to google around and haven't been able to find an answer I could use. I'm still learning recursion, so please excuse any dumb mistakes that might be right in front of me.