返回节点列表 Java-Parent 中的树可以有多个子节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7952460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:09:58  来源:igfitidea点击:

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

javadata-structures

提问by crazyTechie

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

我正在尝试编写 java 代码来返回树中的节点列表。这棵树看起来像这

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.

请帮忙。

回答by Maurice Perry

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:

如果节点可以有多个父节点,请将 addAllNodes 的第一行更改为:

    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;
}

回答by npclaudiu