You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现员工树形结构获取经理所有下属 现有代码仅返回直接下属问题

问题原因

你当前的代码仅收集了每个经理的直接下属,没有将下属的所有间接下属合并到当前经理的汇报列表中,所以根节点只能拿到3、6两个直接下级,无法获取他们的下属人员。

修复方案

修改递归逻辑,在处理完子节点后,将子节点的所有下属也追加到当前经理的汇报列表中,修改后的processRecursively方法如下:

public static void processRecursively(Employee topEmployee, Map<Employee, ArrayList<Employee>> resultMap) {
    // 先初始化当前节点的下属列表
    ArrayList<Employee> subList = resultMap.get(topEmployee);
    if (subList == null) {
        subList = new ArrayList<>();
        resultMap.put(topEmployee, subList);
    }
    // 没有直接下属直接返回
    if (topEmployee.sub == null || topEmployee.sub.isEmpty()) {
        return;
    }
    for (Employee employee : topEmployee.sub) {
        // 先添加直接下属
        if (!subList.contains(employee)) {
            subList.add(employee);
        }
        // 递归处理子节点
        processRecursively(employee, resultMap);
        // 把子节点的所有下属也合并到当前节点的列表中
        ArrayList<Employee> childSubs = resultMap.get(employee);
        if (childSubs != null) {
            for (Employee childSub : childSubs) {
                if (!subList.contains(childSub)) {
                    subList.add(childSub);
                }
            }
        }
    }
}

运行效果

修改后运行代码,输出结果符合预期:

key=6
child count : 3
5 8 1 
key=4
child count : 7
3 6 2 4 5 8 1 
key=3
child count : 2
2 4 

内容的提问来源于stack exchange,提问作者Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 13:24:08