In a company which has CEO Bill and a hierarchy of employees. Employees can have a list of other employees reporting to them, which can themselves have reports, and so on. An employee with at least one report is called a manager.
Please implement the closestCommonManager method to find the closest manager (i.e. farthest from the CEO) to two employees. You may assume that all employees eventually report up to the CEO. Assume the following class which you can’t change –
publicstaticclassEmployee {
privatefinalint id;
privatefinal String name;
privatefinal List<Employee> reports;
publicEmployee(int id, String name) {
this.id= id;
this.name= name;
this.reports=new ArrayList<Employee>();
}
/**
* @return an integer ID for this employee, guaranteed to be unique.
*/publicintgetId() {
return id;
}
/**
* @return a String name for this employee, NOT guaranteed to be unique.
*/public String getName() {
return name;
}
/**
* @return a List of employees which report to this employee. This list may be empty, but will
* never be null.
*/public List<Employee>getReports() {
return reports;
}
/**
* Adds the provided employee as a report of this employee.
*/publicvoidaddReport(Employee employee) {
reports.add(employee);
}
}
Given two employees in a company, find the closest common boss of the two employees.
ImplementEmployee closestCommonManager(Employee e1, Employee e2)that will return closest common manager e1 and e2 directly or indirectly reports to.
Bill (CEO)
/|\ DOM SAMIR MICHAEL
/\\ Peter Bob Porter
|\Milton Nina
For example, closestCommonManager(Milton, Nina) = Peter , closestCommonManager(Nina, Porter) = Dom, closestCommonManager(Nina, Samir) = Bill, closestCommonManager(Peter, Nina) = Peter, etc.
However, in this problem we need to find LCA of two nodes in an n-array tree where a node can have zero or many children. It would be straightforward if we had a parent pointer, then we could have simply walked upward from the node toward the closest common anchestor. But in this problem, the node (Employee) doesn’t have a parent pointer. How do we solve it then?