var count = 0;
var NumbOfNodes = function(root){
if(root.left != null){
NumbOfNodes(root.left);
}
count++;
if(root.right != null){
NumbOfNodes(root.right);
}
return count;
}
So I have this function that counts the number of nodes in a tree. It is a recursive function. When I make count a global variable, the function works and returns a proper value. The problem is, I want count to be part of the function. But if I declare count inside the function, it keeps on getting reset and I wont get a proper answer fro the function.
So, is there a way to preserve the value of a variable inside a recursive function. This question can help me in many other coding practices.
What I want (Diagram): Tree --> NumbOfNodes() --> gives me the number of nodes. But I don't want to make a global variable just for it.
Thanks!