Search code examples
javarecursiontreehierarchy

How to implement a function in Java that returns the hierarchy of an employee inside a company


I am given an Employee-class and a List which contains all employees of a company. Now, I want to implement a function findHierarchy(Employee employee) which returns the hierarchy of the corresponding employee.

I.e. imagine the following hierarchy tree:

boss
    department_leader_1
        group_leader_a
            employee_group_a_1
            employee_group_a_2
        group_leader_b
            employee_group_b_1
    department_leader_2

findHierarchy(boss) should return 3, whereas findHierarchy(employee_group_a_1) should return 0 and findHierarchy(group_leader_a) should return 1.

I have already implemented a function findSubordinates(Employee employee, List<employee> allEmployees) which returns a list with all the direct subordinates of a given employee. For example findSubordinates(group_leader_a, allEmployees) would return [ employee_group_a_1, employee_group_a_2 ] and findSubordinates(department_leader_1, allEmployees) would return [group_leader_a, group_leader_b].

Here is my guess as on how to implement findHierarchy():

public static int findHierarchy(Employee employee, List<Employee> allEmployees, int hierarchy) {

        List<Employee> subordinates = findSubordinates(employee, allEmployees);
        
        if (subordinates.size() > 0) {
            hierarchy += 1;
            for (Employee subordinate: subordinates) {
                hierarchy = findHierarchy(subordinate, allEmployees, hierarchy);
            }
        } 
        return hierarchy;
    }

This doesn't seem to be too far off. However, I have troubles thinking about this recursion completely. Does anyone see where the mistake could be?


Solution

  • try to replace

    hierarchy += 1;
    for (Employee subordinate: subordinates) {
         hierarchy = findHierarchy(subordinate, allEmployees, hierarchy);
    }
    

    with

    int currentHierarchy = hierarchy;                 
    for (Employee subordinate: subordinates) {
        hierarchy = Math.max(findHierarchy(subordinate, allEmployees, currentHierarchy + 1), hierarchy);
    }
    

    Math.max is required to prevent a case with overwritting previous long Employee chain with a shorter one