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.
If you’re certain that the structure is a tree (a node cannot have more than one parent), this will list the nodes in depth-first order:
If nodes can have several parents, change the first line of addAllNodes to:
The breadth-first algorithm goes like this: