Returns a list of nodes in a Java node. A parent node can have multiple child nodes
•
Java
I'm trying to write java code to return a list of nodes in the tree
The node class is
class Node{
String label;
List<Node> children;
}
I'm trying this way But I can't 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.
Solution
If you determine that the structure is a tree (nodes cannot have multiple parent nodes), the nodes are listed in depth priority 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 a node can have multiple parent nodes, change the first line of addallnodes to:
if (node != null && !listOfNodes.contains(node)) {
The breadth first algorithm is as follows:
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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
