Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Lowest Common Ancestor algorithm #258

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
update lower common ancestor js
orist22 committed Dec 5, 2018
commit 643d6b21a78b996b0ce9e500ebff01ce4bcddd4d
59 changes: 31 additions & 28 deletions src/algorithms/tree/lowest-common-ancestor/lowestCommonAncestor.js
Original file line number Diff line number Diff line change
@@ -13,36 +13,39 @@
* @param {BinaryTreeNode} rootNode
* @param {Callbacks} [originalCallbacks]
*/
function calcDepth(node){
let depth = 0;
while (node.parent == null) {
node = node.parent;
depth += 1;
}

return depth;
function calcDepth = var function(node) {
let depth = 0;
while (node.parent == null) {
node = node.parent;
depth += 1;
}

return depth;
}

/*lowest common ancestor*/
/* lowest common ancestor */
export default function lca(rootNode, firstNode, secondNode) {
const firstDepth = calcDepth(firstNode);
const secondDepth = calcDepth(secondNode);

for (let i = 0; i < Math.abs(firstDepth - secondDepth); i++) {
if (firstDepth > secondDepth)
firstNode = firstNode.parent;
else
secondNode = secondNode.parent;
}

if (firstNode == secondNode)
resultNode = firstNode;

while (firstNode != secondNode) {
firstNode = firstNode.parent;
secondNode = secondNode.parent;
}

return firstNode;
const firstDepth = calcDepth(firstNode);
const secondDepth = calcDepth(secondNode);
let firstOne = firstNode;
let secondOne = secondNode;

for (let i = 0; i < Math.abs(firstDepth - secondDepth); i = i + 1) {
if (firstDepth > secondDepth) {
firstOne = firstOne.parent;
} else {
secondOne = secondOne.parent;
}
}

if (firstNode === secondNode)
return firstOne;

while (firstOne !== secondOne) {
firstOne = firstOne.parent;
secondOne = secondOne.parent;
}

return firstOne;
}