用java写查子部门的递归算法
时间: 2024-05-13 12:21:01 浏览: 39
Java递归算法遍历部门代码示例
以下是用Java编写的查找子部门的递归算法示例:
```
public class Department {
private String name;
private List<Department> subDepartments;
public Department(String name) {
this.name = name;
this.subDepartments = new ArrayList<>();
}
public String getName() {
return name;
}
public List<Department> getSubDepartments() {
return subDepartments;
}
public void addSubDepartment(Department department) {
subDepartments.add(department);
}
public void removeSubDepartment(Department department) {
subDepartments.remove(department);
}
}
public class DepartmentUtils {
public static List<Department> findSubDepartments(Department department) {
List<Department> subDepartments = new ArrayList<>();
if (department != null) {
subDepartments.add(department);
for (Department subDepartment : department.getSubDepartments()) {
subDepartments.addAll(findSubDepartments(subDepartment));
}
}
return subDepartments;
}
}
// 示例用法
Department rootDepartment = new Department("root");
Department department1 = new Department("department1");
Department department2 = new Department("department2");
Department department3 = new Department("department3");
Department department4 = new Department("department4");
Department department5 = new Department("department5");
rootDepartment.addSubDepartment(department1);
rootDepartment.addSubDepartment(department2);
department1.addSubDepartment(department3);
department1.addSubDepartment(department4);
department3.addSubDepartment(department5);
List<Department> subDepartments = DepartmentUtils.findSubDepartments(rootDepartment);
for (Department subDepartment : subDepartments) {
System.out.println(subDepartment.getName());
}
```
此代码将输出以下内容:
```
root
department1
department3
department5
department4
department2
```
在上面的示例中,我们使用了一个Department类来表示部门,并用一个List来存储子部门。然后,我们定义了一个DepartmentUtils类,其中包含了一个findSubDepartments()方法,它是一个递归方法,用于查找给定部门的所有子部门。该方法接受一个Department对象作为参数,并返回一个List,其中包含了该部门及其所有子部门。
在示例用法中,我们创建了一个根部门,并为其添加了几个子部门。然后,我们调用了findSubDepartments()方法,将根部门作为参数传递给它,并将返回的所有子部门打印出来。
阅读全文