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:
public static List<Node> returnAllNodes(Node node){
List<Node> listOfNodes = new ArrayList<Node>();
addAllNodes(node, listOfNodes);
return listOfNodes;
}
private static void addAllNodes(Node node, List<Node> listOfNodes) {
if (node != null) {
listOfNodes.add(node);
List<Node> children = node.getChildren();
if (children != null) {
for (Node child: children) {
addAllNodes(child, listOfNodes);
}
}
}
}
If nodes can have several parents, change the first line of addAllNodes to:
if (node != null && !listOfNodes.contains(node)) {
The breadth-first algorithm goes like this:
public static List<Node> returnAllNodes(Node node){
List<Node> listOfNodes = new ArrayList<Node>();
if (node != null) {
listOfNodes.add(node);
for(int i = 0; i < listOfNodes.size(); ++i) {
Node n = listOfNodes.get(i);
List<Node> children = n.getChildren();
if (children != null) {
for (Node child: children) {
if (!listOfNodes.contains(child)) {
listOfNodes.add(child);
}
}
}
}
}
return listOfNodes;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With