Created
June 25, 2020 08:46
-
-
Save misterpoloy/1a4db31905eae39cdddcd02efb1d4791 to your computer and use it in GitHub Desktop.
#CodeChallenge Youngest common ancestor in a graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 getTopAncestorDepth(AncestralTree *descendant, AncestralTree *topAncestor) { | |
int depth = 0; | |
while (descendant->name != topAncestor->name) { | |
depth++; | |
descendant = descendant->ancestor; | |
} | |
return depth; | |
} | |
AncestralTree* commonAncestorHelper(AncestralTree* youngest, AncestralTree* older, int diff) { | |
while (diff != 0) { | |
youngest = youngest->ancestor; | |
diff--; | |
} | |
cout << youngest->name << endl; | |
while (youngest->name != older->name) { | |
youngest = youngest->ancestor; | |
older = older->ancestor; | |
} | |
return youngest; | |
} | |
AncestralTree *getYoungestCommonAncestor(AncestralTree *topAncestor, | |
AncestralTree *descendantOne, | |
AncestralTree *descendantTwo) { | |
int depthOne = getTopAncestorDepth(descendantOne, topAncestor); | |
int depthTwo = getTopAncestorDepth(descendantTwo, topAncestor); | |
if (depthOne > depthTwo) { | |
return commonAncestorHelper(descendantOne, descendantTwo, depthOne - depthTwo); | |
} else { | |
return commonAncestorHelper(descendantTwo, descendantOne, depthTwo - depthOne); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.