Created
December 25, 2022 05:30
-
-
Save thmain/ee5a7786ebaf0b9438d02bdf053cdc9e to your computer and use it in GitHub Desktop.
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
'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