-
Notifications
You must be signed in to change notification settings - Fork 0
/
lowest-common-ancestor.js
84 lines (66 loc) · 1.8 KB
/
lowest-common-ancestor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* @author James LaBroy
*
* Lowest Common Ancestor
* Takes an array of an organisations employees and finds the common manager between two employees.
*
* Input as follows:
* Employee1
* Employee2
* Manager Employee
*
*/
"use strict"
var Node = function(data) {
this.data = data;
this.left = null;
this.right = null;
}
var Organisation = function() {
Organisation.prototype.lca = function(root, a, b) {
if (root == null) return null;
if (root.data == a || root.data == b) return root;
var l = null, r = null;
if (root.left != null) l = this.lca(root.left, a, b);
if (root.right != null) r = this.lca(root.right, a, b);
if (l != null && r !== null) return root;
if (l != null) return l;
return r;
};
Organisation.prototype.findInTree = function(root, employee) {
if (root == null) return false;
if (root.data != employee) {
if (root.left != null) root = this.findInTree(root.left, employee);
if (root.right != null) root = this.findInTree(root.right, employee);
}
return root;
};
Organisation.prototype.findEmployeesManager = function(employees) {
var employee1 = employees.shift();
var employee2 = employees.shift();
var tree = null;
for (var i in employees) {
var employee = employees[i].split(" ");
if (tree == null) tree = new Node(employee[0]);
var manager = this.findInTree(tree, employee[0]);
if (manager.left == null) {
manager.left = new Node(employee[1]);
} else {
manager.right = new Node(employee[1]);
}
}
return this.lca(tree, employee1, employee2);
}
};
var employees = [
"Hilary",
"James",
"Sarah Fred",
"Sarah Paul",
"Fred Jenny",
"Jenny James",
"Fred Hilary"
];
var organisation = new Organisation();
var manager = organisation.findEmployeesManager(employees);
console.log(manager);