Created
July 26, 2019 07:41
-
-
Save wataruoguchi/5883f223f0d787e02c0605aa7d324ca5 to your computer and use it in GitHub Desktop.
Lowest Common Ancestor in a Binary Tree
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
// https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/ | |
class Node { | |
constructor(val, left, right) { | |
this.val = val; | |
this.left = left; | |
this.right = right; | |
}; | |
} | |
function getLCA(root, n1, n2) { | |
// The condition of finishing recursive: | |
// 1. When node is null. | |
// 2. When node is same as n1 or n2. | |
if (!root) return null; | |
if (root.val === n1 || root.val === n2) { | |
return root; | |
} | |
const left = getLCA(root.left, n1, n2); | |
const right = getLCA(root.right, n1, n2); | |
if (left && right) { | |
// 3. When left and right are both defined, return the ancestor. | |
return root; | |
} | |
// 4. If one of them is defined, return the one that we found | |
return left ? left : right; | |
} | |
const root = new Node(1); | |
root.left = new Node(2); | |
root.right = new Node(3); | |
root.left.left = new Node(4); | |
root.left.right = new Node(5); | |
root.right.left = new Node(6); | |
root.right.right = new Node(7); | |
const res = [[4,5], [4,6], [3,4], [2,4]].map((params) => getLCA(root, ...params).val).join(','); | |
console.log(res === '2,1,1,2'); | |
// https://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-binary-tree/1 | |
const example1 = new Node(1); | |
example1.left = new Node(2); | |
example1.right = new Node(3); | |
const example1Res = [[2,3]].map((params) => getLCA(example1, ...params).val).join(','); | |
console.log(example1Res === '1'); | |
const example2 = new Node(5); | |
example2.left = new Node(2); | |
example2.left.left = new Node(3); | |
example2.left.right = new Node(4); | |
const example2Res = [[3,4]].map((params) => getLCA(example2, ...params).val).join(','); | |
console.log(example2Res === '2'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment