forked from adamespii/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem_112.js
42 lines (37 loc) Β· 980 Bytes
/
problem_112.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for a binary tree node with parent pointers
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* this.parent = null;
* }
*/
/**
* Finds lowest common ancestor of two nodes
* @param {TreeNode} v
* @param {TreeNode} w
* @return {TreeNode}
*/
function leastCommonAcestor(v, w) {
// Find root node
let root = v;
while (root !== null) {
root = root.parent;
}
return findLCAPath(root, v, w);
}
/**
* Recursive helper function
* @param {TreeNode} currNode
* @param {TreeNode} v
* @param {TreeNode} w
* @return {TreeNode}
*/
function findLCAPath(root, v, w) {
if (!root || root === v || root === w) return root;
const left = findLCAPath(root.left, v, w);
const right = findLCAPath(root.right, v, w);
if (!left) return right; // v and w are in the right subtree
if (!right) return left; // v and w are in the left subtree
return root; // v is in one side and w is in the other
}