Skip to content

Instantly share code, notes, and snippets.

@thmain
Created December 25, 2022 05:30
Show Gist options
  • Save thmain/ee5a7786ebaf0b9438d02bdf053cdc9e to your computer and use it in GitHub Desktop.
Save thmain/ee5a7786ebaf0b9438d02bdf053cdc9e to your computer and use it in GitHub Desktop.
'use strict';
function commonAncestor(n1, n2) {
var inOrderTra = inOrder(this);
var postOrderTra = postOrder(this);
var i1 = inOrderTra.indexOf(n1);
var i2 = inOrderTra.indexOf(n2);
var middleNodes = inOrderTra.splice(i1 + 1, i2);
var map = middleNodes.map(function(i) {
return {
i: postOrderTra.indexOf(i)
};
});
// Find the node with the highest index value
return Object.keys(map).reduce(function(a, b) {
return map[a] > map[b] ? a : b;
});
}
/*
Returns an array containing all the elements in the in-order traversal.
@param {BT} root
*/
function inOrder(root) {
...
}
/*
Returns an array containing all the elements in the post-order traversal.
@param {BT} root
*/
function postOrder(root) {
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment