private int getDepth(AncestralTree topAncestor, AncestralTree descendant) { var depth = 0; while (descendant != topAncestor) { depth++; descendant = descendant.ancestor; } return(depth); }
public AncestralTree GetYoungestCommonAncestor(AncestralTree topAncestor, AncestralTree descendantOne, AncestralTree descendantTwo) { var firstDescDepth = getDepth(topAncestor, descendantOne); var secondDescDepth = getDepth(topAncestor, descendantTwo); if (firstDescDepth > secondDescDepth) { return(backtrackingToAncestral(descendantOne, descendantTwo, firstDescDepth - secondDescDepth)); } else { return(backtrackingToAncestral(descendantTwo, descendantOne, secondDescDepth - firstDescDepth)); } }
private AncestralTree backtrackingToAncestral(AncestralTree lowestDescendant, AncestralTree topDescendant, int depthDiff) { //Get the lowestDescendant to the same leve as topDescendant while (depthDiff != 0) { depthDiff--; lowestDescendant = lowestDescendant.ancestor; } while (lowestDescendant != topDescendant) { lowestDescendant = lowestDescendant.ancestor; topDescendant = topDescendant.ancestor; } return(lowestDescendant); }
public AncestralTree(char name) { this.name = name; this.ancestor = null; }