title: Creating a list of leaves recursively in a binary tree java
body: <p>My recursive function to count number of leaves in a Binary Tree works correctly:</p>
  
  <pre><code>public static int numberOfLeaves(BinaryTree&lt;String&gt; root) {
  
      if (root == null) return 0;
      else if(root.isLeaf()) return 1;
      int left = numberOfLeaves(root.leftTree);
      int right = numberOfLeaves(root.rightTree);
      return (left + right);
  }
  </code></pre>
  
  <p>But now I want to sum up the data of all the leaves in a <code>List</code> and <strong>return</strong> it. </p>
  
  <p>Have a look at my hopeless attempt:</p>
  
  <pre><code>public ArrayList&lt;String&gt; getDataLeaves(BinaryTree&lt;String&gt; root) {
  
      ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();
  
      if (root == null) return list;
      else if (root.isLeaf()) list.add(root.data);
      else if(root.leftTree != null ) getDataLeaves(root.leftTree);
      else getDataLeaves(root.rightTree);
  
      return list;
  }
  </code></pre>
  
  <p>Can I (how do I) use the functionality/style of my <em>numberOfLeaves</em> function to help me write a <strong>recursive</strong> function which will sum up the data of all the leaves in a <strong>list</strong> and <strong>return</strong> it.</p>
  
  <p>Note:
  a <strong>node</strong> is of type <code>BinaryTree&lt;String&gt;</code>
  with <code>data</code>, <code>leftTree</code>,<code>RightTree</code> as instance variables.</p>