Compare Ancestral Nodes
Wed Sep 15 2021 15:50:27 GMT+0000 (UTC)
Saved by
@Adorism80
#javascript
class AncestralTree {
constructor(name, ancestorNode) {
this.name = name;
this.ancestor = ancestorNode;
}
}
const a = new AncestralTree("A", null);
const b = new AncestralTree("B", a);
const d = new AncestralTree("D", b);
const e = new AncestralTree("E", b);
const c = new AncestralTree("c", a);
const f = new AncestralTree("F", c);
const g = new AncestralTree("G", c);
const h = new AncestralTree("H", d);
const i = new AncestralTree("I", d);
function ancestorFunc(topAnc, desc1, desc2) {
const list1 = ancList(desc1);
const list2 = ancList(desc2);
//list1 = [A, B, D]
//list2 = [A, B]
for (let i = 0; i < list1.length; i++) {
if (list1[i] !== list2[i]) {
return list1[i - 1].name
}
}
}
function ancList (myNode) {
let node = myNode
let ancestors = [];
while (node){
ancestors.unshift(node)
node = node.ancestor
}
return ancestors;
}
console.log(ancestorFunc(a, h, i))
content_copyCOPY
Comments
@Adorism80 - Wed Sep 15 2021 15:52:19 GMT+0000 (UTC)Compare two nodes in a tree to find the youngest ancestor they share