Nothing wrong with the answers given, but I thought I'd give a slight variation. I prefer to avoid the conditionals inside the loop if possible, which you can with some slight rearranging of the code. In the following example, I show both a Java 8 lambda version and a pre-Java 8. In this case, the Java 8 code doesn't really buy you anything, but I threw it in there anyway.
I created a custom Node class in order to see output
public class ListAdd {
public static void main(String[] args) {
Node node = new Node(0);
addChildren(3,node);
addChildren(4,node.getChildren().get(0));
addChildren(2,node.getChildren().get(2));
addChildren(1,node.getChildren().get(2).getChildren().get(0));
addChildren(2,node.getChildren().get(2).getChildren().get(0).getChildren().get(0));
List<Node> allNodes = getAllNodes(node,new ArrayList<>());
System.out.println("------------------------\nTotal number of nodes: " + allNodes.size());
allNodes.forEach(System.out::println);
allNodes = getAllNodesOld(node, new ArrayList<>());
System.out.println("------------------------\nTotal number of nodes: " + allNodes.size());
allNodes.forEach(System.out::println);
}
public static List<Node> getAllNodes(Node parent, List<Node> allNodes){
if(parent == null || parent.getChildren().size() < 1){
return allNodes;
}
parent.getChildren()
.forEach(node -> {
allNodes.add(node);
getAllNodes(node,allNodes);
});
return allNodes;
}
public static List<Node> getAllNodesOld(Node parent, List<Node> allNodes){
if(parent == null || parent.getChildren().size() < 1){
return allNodes;
}
for(Node node : parent.getChildren()){
allNodes.add(node);
getAllNodesOld(node, allNodes);
}
return allNodes;
}
public static void addChildren(int amount, Node parent){
for(int i=0;i<amount;i++){
parent.addChild(new Node(i + (parent.getVal() + 1)));
}
}
public static class Node{
List<Node> children = new ArrayList<>();
int val;
public Node(int v){
val = v;
}
public void addChild(Node node){
children.add(node);
}
public List<Node> getChildren(){
return children;
}
public int hashCode(){
return 31 * val * (children.size() + 1);
}
public int getVal(){
return val;
}
public boolean equals(Object o){
if(o == this) return true;
if(!(o instanceof Node)) return false;
Node n = (Node)o;
return val == n.val && children.containsAll(n.children);
}
public String toString(){
return "Node{val="+val+",children="+children+"}";
}
}
}