Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package lca;
- import java.util.ArrayList;
- import java.util.List;
- public class Company {
- public static void main(String[] args) {
- /*
- * Initech Test Example from PDF
- */
- Employee milton = new Employee(8, "Milton");
- Employee nina = new Employee(9, "Nina");
- Employee bob = new Employee(5, "Bob");
- Employee peter = new Employee(6, "Peter");
- Employee porter = new Employee(7, "Porter");
- Employee dom = new Employee(2, "DOM");
- Employee samir = new Employee(3, "Samir");
- Employee michael = new Employee(4, "Michael");
- Employee bill = new Employee(1, "Bill");
- // Fourth Row
- peter.addReport(milton);
- peter.addReport(nina);
- // Third Row
- dom.addReport(bob);
- dom.addReport(peter);
- dom.addReport(porter);
- // Second Row
- bill.addReport(dom);
- bill.addReport(samir);
- bill.addReport(michael);
- Employee closestMgr = closestCommonManager(bill, milton, porter);
- System.out.println("Closest Common Manager between Milton and Porter is: " + closestMgr.getName());
- }
- // IMPORTANT: DO NOT MODIFY THIS CLASS
- public static class Employee {
- private final int id;
- private final String name;
- private List<Employee> reports;
- public Employee(int id, String name) {
- this.id = id;
- this.name = name;
- this.reports = new ArrayList<Employee>();
- }
- public int getId() {
- return id;
- }
- public String getName() {
- return name;
- }
- public List<Employee> getReports() {
- return reports;
- }
- public void addReport(Employee employee) {
- reports.add(employee);
- }
- }
- /*
- * Read the attached PDF for more explanation about the problem
- * Note: Don't modify the signature of this function
- * @param ceo
- *
- * @param firstEmployee
- *
- * @param secondEmployee
- *
- * @return common manager for both employees that is closest to them.
- */
- public static Employee closestCommonManager(Employee ceo, Employee firstEmployee, Employee secondEmployee) {
- // Implement me
- /*
- * This is a Office Space version of the
- * k-ary tree lowest common ancestor algorithm
- */
- // immediate match found
- if(firstEmployee == ceo || secondEmployee == ceo) {
- return ceo;
- }
- Employee employeeResult = null;
- int count = 0;
- /*
- * Descend the k-ary from the top down
- * by iterating the ceo(manager's) children
- * recursively until you get a non-null value
- */
- for (Employee reportingEmployee : ceo.getReports()) {
- Employee e = closestCommonManager(reportingEmployee, firstEmployee, secondEmployee);
- if (e != null) {
- count++;
- employeeResult = e;
- }
- }
- // 2 non-null recursive results means a match, return the common ancestor
- if (count == 2) {
- return ceo;
- }
- return employeeResult;
- }
- };
Add Comment
Please, Sign In to add comment