package com.example.demo;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class DepartmentTest {
public static void main(String[] args) {
List<Department> allDepartment = new ArrayList<>();
Department dep1 = new Department(1, 0, "北京总部");
Department dep3 = new Department(3, 1, "研发中心");
Department dep4 = new Department(4, 3, "后端研发组");
Department dep6 = new Department(6, 4, "后端实习生组");
Department dep7 = new Department(7, 3, "前端研发组");
Department dep8 = new Department(8, 1, "产品部");
allDepartment.add(dep6);
allDepartment.add(dep7);
allDepartment.add(dep8);
allDepartment.add(dep1);
allDepartment.add(dep3);
allDepartment.add(dep4);
List<Department> subDepartments = DepartmentTest.getSub(3, allDepartment);
for (Department subDepartment : subDepartments) {
System.out.println(subDepartment);
}
}
/**
* 根据id,获取所有子部门列表(包括隔代子部门,一直到叶子节点)
* 要求:不能新增参数,不能增加static变量
* @param pid
* @return
*/
public static List<Department> getSub(int pid, List<Department> allDepartment) {
return getSubList(pid, allDepartment);
}
public static List<Department> getSubList(int pid, List<Department> allDepartment){
List<Department> subDepartment = new ArrayList<>();
for (Department department : allDepartment ) {
if(department.getPid() == pid){
subDepartment.add(department);
}
}
if(CollectionUtils.isEmpty(subDepartment)){
return subDepartment;
}
for (Department department : allDepartment ) {
if(department.getPid() == pid){
List<Department> subList = getSubList(department.getId(), allDepartment);
subDepartment.addAll(subList);
}
}
return subDepartment;
}
}
class Department {
/** id */
private int id;
/** parent id */
private int pid;
/** 名称 */
private String name;
public Department(int id, int pid, String name) {
this.id = id;
this.pid = pid;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Department{" +
"id=" + id +
", pid=" + pid +
", name='" + name + '\'' +
'}';
}
}
一道编程题
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 对程序员来说,程序的魅力在于它的变化无穷,对于一门计算机语言来说,他的基础语法是固定有限的,可是编程的花样却是千变...
- 题目:输入一个年份,判断该年份是否为闰年 提示:闰年的条件为:四年一闰,百年不闰,四百年再闰。 则根据可知核心判断...
- 原题来自Google CodeJam 2017 Round C的第四题4M Corporation,大意如下: 给...