Java 树状结构递归获取所有子节点:示例与代码

本文将展示如何使用递归在 Java 中遍历树状结构并获取所有子节点。

树状结构示例

以下是一个简单的 Java 树状结构示例,包含一个 Node 类和一个 Tree 类:

class Node {
    private String name;
    private List<Node> children;
    
    public Node(String name) {
        this.name = name;
        this.children = new ArrayList<>();
    }
    
    public String getName() {
        return this.name;
    }
    
    public void addChild(Node child) {
        this.children.add(child);
    }
    
    public List<Node> getChildren() {
        return this.children;
    }
}

class Tree {
    private Node root;
    
    public Tree(Node root) {
        this.root = root;
    }
    
    public Node getRoot() {
        return this.root;
    }
}

递归获取所有子节点

现在我们可以使用递归来遍历树并获取所有子节点。假设我们想要获取从根节点开始的所有子节点:

public List<Node> getAllChildren(Node node) {
    List<Node> children = new ArrayList<>();
    for (Node child : node.getChildren()) {
        children.add(child);
        children.addAll(getAllChildren(child));
    }
    return children;
}

这个方法将会递归地遍历所有子节点,将它们添加到一个列表中并返回该列表。

示例代码

以下是如何调用该方法的示例:

Node root = new Node('root');
Node child1 = new Node('child1');
Node child2 = new Node('child2');
Node grandchild1 = new Node('grandchild1');
Node grandchild2 = new Node('grandchild2');

root.addChild(child1);
root.addChild(child2);
child1.addChild(grandchild1);
child2.addChild(grandchild2);

Tree tree = new Tree(root);
List<Node> allChildren = tree.getAllChildren(tree.getRoot());

for (Node node : allChildren) {
    System.out.println(node.getName());
}

这将会输出以下内容:

child1
grandchild1
child2
grandchild2

总结

通过使用递归,我们可以轻松地遍历树状结构并获取所有子节点。这种方法简洁高效,并且易于理解和实现。

Java 树状结构递归获取所有子节点:示例与代码