Hello guys,
i'm studying the Java programming language. every thins were going very well, but once i have encountered RECURSION i started to feel so bad.
there is a recursive method that is blowing my mind. I can't figure out how does it print that the sum of a set of numbers without using a variable that keeps track of the current value of the sum.
My problem is that i totally understood how recursion is working however, when i try to write a recursive method, i fail.
Here is the method. i wish you could help me understand it.
/**
* Return the number of leaves in the tree to which node points.
*/
static int countLeaves(TreeNode node) {
if(node == null){
return 0;
} else if(node.left == null && node.right == null){
return 1;
} else {
return countLeaves(node.left) + countLeaves(node.right);
}
} // end countNodes()
Best regards,