-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathyoungest-common-ancestor.cpp
51 lines (46 loc) · 1.13 KB
/
youngest-common-ancestor.cpp
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
#include <vector>
using namespace std;
class AncestralTree {
public:
char name;
AncestralTree* ancestor;
AncestralTree(char name) {
this->name = name;
this->ancestor = NULL;
}
void addAsAncestor(vector<AncestralTree*> descendants);
};
int depthOfDescendent(AncestralTree* top, AncestralTree* des) {
int depth = 0;
while (des != top) {
des = des->ancestor;
depth++;
}
return depth;
}
AncestralTree* getYoungestCommonAncestor(
AncestralTree* topAncestor,
AncestralTree* descendantOne,
AncestralTree* descendantTwo
) {
// Write your code here.
int d1 = depthOfDescendent(topAncestor, descendantOne);
int d2 = depthOfDescendent(topAncestor, descendantTwo);
int diff = d1 < d2 ? d2 - d1 : d1 - d2;
if (d1 < d2) {
while (diff) {
descendantTwo = descendantTwo->ancestor;
diff--;
}
} else if (d1 > d2) {
while (diff) {
descendantOne = descendantOne->ancestor;
diff--;
}
}
while (descendantOne != descendantTwo) {
descendantOne = descendantOne->ancestor;
descendantTwo = descendantTwo->ancestor;
}
return descendantOne;
}