title: Simple recursion function to save values to List
body: <p>This question relates to recursion. Consider the program shown below (not my real code, but this explains the problem I have).</p>
  
  <p>The function <strong>must</strong> use recursion as shown, and what I want to do is have a way that each leaf value instead of getting printed out, is saved to a list. So finally I get a <code>List&lt;String&gt;</code> that when I print out gives me the contents of each leaf node.</p>
  
  <pre><code>String xml = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n" +
  "&lt;title text=\"title1\"&gt;\n" +
  "    &lt;comment id=\"comment1\"&gt;\n" +
  "        &lt;data&gt; abcd &lt;/data&gt;\n" +
  "        &lt;data&gt; efgh &lt;/data&gt;\n" +
  "    &lt;/comment&gt;\n" +
  "    &lt;comment id=\"comment2\"&gt;\n" +
  "        &lt;data&gt; ijkl &lt;/data&gt;\n" +
  "        &lt;data&gt; mnop &lt;/data&gt;\n" +
  "        &lt;data&gt; qrst &lt;/data&gt;\n" +
  "    &lt;/comment&gt;\n" +
  "&lt;/title&gt;\n";
  
  DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  Document doc = builder.parse(new InputSource(new StringReader(xml)));
  
  List&lt;String&gt; results = traverse(doc.getFirstChild());
  
  //Want to print out results list here...
  
  public static List&lt;String&gt; traverse(Node node){
      System.out.println(node.getNodeName());
      for(int i = 0; i &lt; node.getChildNodes().getLength(); i++){
          traverse(node.getChildNodes().item(i));         
      }
      return null;
  }
  </code></pre>
  
  <p>So my question is, how can I re-write the traverse function in a way that, it still uses recursion but saves all leaf nodes to the list. And then it returns the list of all values.</p>