title: Find size of Binary Tree recursively
body: <p>I have implemented the function to find size of a binary tree using recursion (referencing a book on Data Structures and Algorithms)</p>
  
  <p>The code snippet looks like:</p>
  
  <pre><code>// Returns the total number of nodes in this binary tree (include the root in the count).
  public static int size(BinaryTreeNode root) {
      int leftCount = root.left == null ? 0 : size(root.left);
      int rightCount = root.right == null ? 0 : size(root.right);
      return 1 + leftCount + rightCount;
  }
  </code></pre>
  
  <p>And it works as well.
  However I am unable to understand how the leftCount and rightCount elements get incremented between recursive function calls? Shouldn't it be done like below:</p>
  
  <pre><code>// Returns the total number of nodes in this binary tree (include the root in the count).
  public static int size(BinaryTreeNode root) {
      int leftCount = 0;
      int rightCount = 0;
      leftCount = leftCount + (root.left == null ? 0 : size(root.left));
      rightCount = rightCount+ (root.right == null ? 0 : size(root.right));
      return 1 + leftCount + rightCount;
  }
  </code></pre>
  
  <p>For some reason both the functions yield same result (7, which is correct) for the Binary Tree below.</p>
  
  <p><a href="https://i.stack.imgur.com/sYJX6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sYJX6.png" alt="Example Problem"></a></p>