Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created June 25, 2020 08:46
Show Gist options
  • Save misterpoloy/1a4db31905eae39cdddcd02efb1d4791 to your computer and use it in GitHub Desktop.
Save misterpoloy/1a4db31905eae39cdddcd02efb1d4791 to your computer and use it in GitHub Desktop.
#CodeChallenge Youngest common ancestor in a graph
#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);
}
}
@misterpoloy
Copy link
Author

misterpoloy commented Jun 25, 2020

code ancestor

CodeChallenge Youngest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment