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 LCA algorithm
orist22 committed Dec 5, 2018
commit ee00302873a4462084155346d6bff4299fb6d188
17 changes: 11 additions & 6 deletions src/algorithms/tree/lowest-common-ancestor/lowestCommonAncestor.js
Original file line number Diff line number Diff line change
@@ -15,8 +15,10 @@
*/
function calcDepth(node) {
let depth = 0;
while (node.parent == null) {
node = node.parent;
let tempNode = null;
tempNode = node;
while (tempNode.parent == null) {
tempNode = tempNode.parent;
depth += 1;
}

@@ -27,9 +29,11 @@ function calcDepth(node) {
export default function lca(rootNode, firstNode, secondNode) {
const firstDepth = calcDepth(firstNode);
const secondDepth = calcDepth(secondNode);
let firstOne = firstNode;
let secondOne = secondNode;

let firstOne = null;
let secondOne = null;
firstOne = firstNode;
secondOne = secondNode;

for (let i = 0; i < Math.abs(firstDepth - secondDepth); i = i + 1) {
if (firstDepth > secondDepth) {
firstOne = firstOne.parent;
@@ -38,8 +42,9 @@ export default function lca(rootNode, firstNode, secondNode) {
}
}

if (firstNode === secondNode)
if (firstNode === secondNode) {
return firstOne;
}

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