I am trying to write java code to return list of Nodes in a tree. The tree looks like
Node class is
class Node{
String label;
List<Node> children;
}
I am trying this way. But not able to understand how to write a loop to traverse.
public List<Node> returnAllNodes(Node node){
List<Node> listOfNodes =
new ArrayList<Node>();
boolean iterationCompleted = false;
if(node==null){
return null;
}
while(!iterationCompleted){
if(node.getChildren()==null){
listOfNodes.add(node);
break;
}
else{
//
}
}
return null;
//return traverseAndReturnAllNodes(node.getChildren().get(0));
}
Please help.
Node
s for where you are, but that's not so elegant). Each iteration of the while look (posh for loop would be better) shouldadd
the child node andaddAll
the list from the recursive call to get the child node's descendents. (There are some changes you can make to get the lists back in different orders.) – Schutzstaffel