java递归查询部门人数
时间: 2024-08-13 15:01:06 浏览: 157
Java中的递归是一种函数直接或间接地调用自身的方式来解决问题的技术。当涉及到查询特定结构(如树、图等)的数据时,递归通常是一个非常有用的工具。例如,在组织架构(如部门层级)中查找某个部门的人数就是一个典型的适用于递归算法的问题。
下面是一个基本的示例,展示了如何通过递归来查询部门人数:
```java
class Department {
private String name;
private int count; // 用于记录当前部门的人数
private List<Department> subDepartments; // 存储下级部门
public Department(String name) {
this.name = name;
this.count = 0;
this.subDepartments = new ArrayList<>();
}
public void addSubDepartment(Department department) {
subDepartments.add(department);
}
/**
* 使用递归计算部门人数
*/
public int getEmployeeCount() {
return getCount(this);
}
private static int getCount(Department department) {
if (department == null) {
return 0;
}
// 统计当前部门的人数
int currentCount = department.getCount();
// 遍历并统计所有子部门的人数
for (Department sub : department.getSubDepartments()) {
currentCount += getCount(sub);
}
return currentCount;
}
}
```
这个例子中定义了一个`Department`类,它包含了部门名称、员工数目以及下级部门列表。`getEmployeeCount()`方法使用递归遍历所有下属部门,并累加每个部门的员工数目,最终返回整个部门的总人数。
-
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)