I want to count the no of leaf nodes: Note:Cannot use global/class level variable I implmeted following algo, and it works fine.But i want method signature to be
countLeaves(Node node)
I know that i can overload methds and call the 2 args method sig from 1 args, but dont want to do so.Can anyone suggest any other method?
int countLeaves(Node node,int count){
if(node==null)
return 0;
if(node.left==null && node.right==null){
return 1+count;
}else{
int lc = countLeaves(node.left, count);
int total = countLeaves(node.right, lc);
return total;
}
}
int countLeaves(Node node){
if( node == null )
return 0;
if( node.left == null && node.right == null ) {
return 1;
} else {
return countLeaves(node.left) + countLeaves(node.right);
}
}
You are doing the same thing as before but instead of holding the current count as we go, we simply say return the result of the sum of the left and right node. These in turn recurse down till they hit the basecases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With