Skip to content

Commit 031180e

Browse files
Create Lowest_Common_Ancestor_of_a_Binary_Tree.js
1 parent 1bc0f47 commit 031180e

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
Lowest Common Ancestor of a Binary Tree
3+
4+
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
5+
6+
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
7+
8+
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
9+
10+
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
11+
12+
_______3______
13+
/ \
14+
___5__ ___1__
15+
/ \ / \
16+
6 _2 0 8
17+
/ \
18+
7 4
19+
Example 1:
20+
21+
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
22+
Output: 3
23+
Explanation: The LCA of nodes 5 and 1 is 3.
24+
Example 2:
25+
26+
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
27+
Output: 5
28+
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself
29+
according to the LCA definition.
30+
Note:
31+
32+
All of the nodes' values will be unique.
33+
p and q are different and both values will exist in the binary tree.
34+
*/
35+
36+
var lowestCommonAncestor = function(root, p, q) {
37+
if(root === null) {
38+
return root;
39+
}
40+
if(p.val === root.val) {
41+
return p;
42+
}
43+
if(q.val === root.val) {
44+
return q;
45+
}
46+
if(lowestCommonAncestor(root.left, p, q));
47+
const right = lowestCommonAncestor(root.right, p, q);
48+
if(left !== null && right !== null) {
49+
return root;
50+
}
51+
return left !== null ? left : right;
52+
};
53+
54+
var lowestCommonAncestor1 = function(root, p, q) {
55+
const pathToP = pathTo(root, p.val);
56+
const pathToQ = pathTo(root, q.val);
57+
var elem = null;
58+
for(var i = 0; i < Math.min(pathToP.length, pathToQ.length); i++) {
59+
if(pathToP[i] !== pathToQ[i]) {
60+
return pathToP[i - 1];
61+
}
62+
}
63+
64+
return elem;
65+
};
66+
67+
var pathTo = function(root, a) {
68+
if(root === null) {
69+
return null;
70+
}
71+
if(root.val === a) {
72+
return [root.val];
73+
}
74+
const left = pathTo(root.left, a);
75+
if (left !== null) {
76+
return [root.val] + left;
77+
}
78+
const right = pathTo(root.right, a);
79+
if(right !== null) {
80+
return [root.val] + right;
81+
}
82+
return null;
83+
}
84+
85+

0 commit comments

Comments
 (0)