java使用递归查询父类别的所有后代
时间: 2023-09-01 20:06:34 浏览: 44
您可以使用递归来查询父类别的所有后代。以下是一个示例的Java代码:
```java
import java.util.ArrayList;
import java.util.List;
class Category {
private String name;
private List<Category> children;
public Category(String name) {
this.name = name;
this.children = new ArrayList<>();
}
public void addChild(Category category) {
children.add(category);
}
public List<Category> getChildren() {
return children;
}
public String getName() {
return name;
}
}
public class CategoryHierarchy {
public static void main(String[] args) {
// 创建类别层级结构
Category root = new Category("Root");
Category electronics = new Category("Electronics");
Category smartphones = new Category("Smartphones");
Category laptops = new Category("Laptops");
Category clothing = new Category("Clothing");
Category menClothing = new Category("Men's Clothing");
Category womenClothing = new Category("Women's Clothing");
root.addChild(electronics);
electronics.addChild(smartphones);
electronics.addChild(laptops);
root.addChild(clothing);
clothing.addChild(menClothing);
clothing.addChild(womenClothing);
// 查询父类别的所有后代
List<Category> descendants = new ArrayList<>();
getAllDescendants(root, descendants);
// 打印结果
System.out.println("所有后代类别:");
for (Category category : descendants) {
System.out.println(category.getName());
}
}
public static void getAllDescendants(Category category, List<Category> descendants) {
descendants.add(category);
for (Category child : category.getChildren()) {
getAllDescendants(child, descendants);
}
}
}
```
在上面的示例中,我们创建了一个Category类来表示类别,每个类别都有一个名称和一个子类别的列表。使用递归的方式,我们在getAllDescendants方法中遍历父类别的所有子类别,并将它们添加到后代列表中。最后,我们打印出所有的后代类别。