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

如何用Java实现查询公司员工层级的findHierarchy函数并排查递归错误

问题修正方案

原代码错误点

  • 核心逻辑偏差:需求统计的是当前员工到最底层无下属员工的最大深度,无下属的叶子员工返回0,非叶子员工的层级为「1 + 所有下属层级的最大值」。原代码采用从上到下累加层级的逻辑,额外传入的hierarchy参数属于多余设计,和需求逻辑完全不匹配。
  • 遍历逻辑错误:遍历下属时直接将递归返回值赋值给hierarchy,只会保留最后一个下属的递归计算结果,没有取所有下属层级的最大值,最终返回结果偏大且不稳定。

修正后代码

public static int findHierarchy(Employee employee, List<Employee> allEmployees) {
    List<Employee> subordinates = findSubordinates(employee, allEmployees);
    // 无下属为叶子节点,直接返回0
    if (subordinates.isEmpty()) {
        return 0;
    }
    int maxSubLevel = 0;
    // 遍历所有下属,取下属层级的最大值
    for (Employee subordinate : subordinates) {
        int currentSubLevel = findHierarchy(subordinate, allEmployees);
        maxSubLevel = Math.max(maxSubLevel, currentSubLevel);
    }
    // 当前节点层级 = 下属最大层级 + 1
    return maxSubLevel + 1;
}

结果验证

对应示例层级树的计算结果完全符合要求:

  • 无下属的底层员工employee_group_a_1返回0
  • 下属均为底层员工的group_leader_a返回1
  • 根节点boss的下属最大层级为2,最终返回3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 20:06:06