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
``
原文地址: https://www.cveoy.top/t/topic/hb4z 著作权归作者所有。请勿转载和采集!