Simple recursion function to save values to List
This question relates to recursion. Consider the program shown below (not my real code, but this explains the problem I have).
The function must 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 List<String>
that when I print out gives me the contents of each leaf node.
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<title text=\"title1\">\n" +
" <comment id=\"comment1\">\n" +
" <data> abcd </data>\n" +
" <data> efgh &l开发者_运维问答t;/data>\n" +
" </comment>\n" +
" <comment id=\"comment2\">\n" +
" <data> ijkl </data>\n" +
" <data> mnop </data>\n" +
" <data> qrst </data>\n" +
" </comment>\n" +
"</title>\n";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
List<String> results = traverse(doc.getFirstChild());
//Want to print out results list here...
public static List<String> traverse(Node node){
System.out.println(node.getNodeName());
for(int i = 0; i < node.getChildNodes().getLength(); i++){
traverse(node.getChildNodes().item(i));
}
return null;
}
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.
This one stores in a List the same Strings you print with your traverse function and you don't need to pass the List as an argument:
public static List<String> traverse( Node node ) {
List<String> results = new LinkedList();
results.add(node.getNodeName());
if ( node.getChildNodes().getLength() > 0 ) {
for ( int i = 0; i < node.getChildNodes().getLength(); i++ )
results.addAll(traverse(node.getChildNodes().item(i)));
}
return results;
}
You could either return a list and add the elements from the recursive calls to the result list of the current call or pass the list as a parameter and add the result directly.
I think what you want is something like this:
public static void traverse(Node node, List<String> results) {
if (node.getChildNodes().getLength() == 0) {
// leaf node
results.add(node.getNodeValue());
}
else {
// walk all children
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
traverse(node.getChildNodes().item(i));
}
}
}
public static List<String> traverse(Node node) {
List<String> result = new LinkedList<String>();
traverse(node,result);
return result;
}
精彩评论