2

I am unable to understand why my counter is unable to store the correct value.

This code works when I keep the counter as a universal variable, but it doesn't work if I pass the "count" in the function

public int numberOfLeaves(TreeNode root) {   
    if(root==null)
       return 0;

    return leaves(root,0);
}



public int leaves(TreeNode TN,int count){ 

  if(TN.left==null && TN.right==null) {     
       count++;     
  }

  if(TN.left!=null){
       leaves(TN.left,count); 
  }

  if(TN.right!=null){
      leaves(TN.right,count);   
  }    

return count;

}
User_110
  • 21
  • 1
  • 5
    You don't save the return value from the method call. `count += leaves(TN.left,count);` – Nexevis Aug 28 '19 at 15:01
  • 2
    Remember that in java, variables are [passed by value](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – jhamon Aug 28 '19 at 15:09
  • @jhamon I agree they are passed by value, but i am passing the most updated value in the function call. – User_110 Aug 28 '19 at 16:11
  • yea, you pass the value, then what? You change it in the method, return it, and... drop it. The int value changed in the callee method is not updated in the caller method – jhamon Aug 28 '19 at 16:16
  • Ok, I get what you mean. Thank you! I updated the call to "count=leaves(TN.left,count);" which fixed the issue. – User_110 Aug 28 '19 at 16:21

1 Answers1

0

You do not even need to pass a count variable. Recursion does that work for you.

You simply need to add the leaf count of left subtree + the leaf count of right subtree:

public int leaves(TreeNode TN) {
    if(TN == null)
        return 0;

    if(TN.left == null && TN.right == null)
        return 1;

    return leaves(TN.left) + leaves(TN.right);
}
arcadeblast77
  • 560
  • 2
  • 12