Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return list of Nodes a Tree in Java-Parent can have multiple child Nodes

I am trying to write java code to return list of Nodes in a tree. The tree looks like this

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.

like image 872
crazyTechie Avatar asked Oct 31 '11 10:10

crazyTechie


1 Answers

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;
}
like image 78
Maurice Perry Avatar answered Nov 14 '22 23:11

Maurice Perry