Skip to content

Commit e40abc4

Browse files
committed
added description
1 parent e26874d commit e40abc4

File tree

1 file changed

+30
-0
lines changed
  • Lowest Common Ancestor of a Binary Tree

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/*
9+
* @param {TreeNode} root
10+
* @param {TreeNode} p
11+
* @param {TreeNode} q
12+
* @return {TreeNode}
13+
*/
14+
var lowestCommonAncestor = function(root, p, q) {
15+
let currNode = root
16+
17+
if (currNode === null) return currNode
18+
19+
if (currNode.val == p.val || currNode.val == q.val) {
20+
return currNode
21+
}
22+
23+
let lVal = lowestCommonAncestor(currNode.left, p, q)
24+
let rVal = lowestCommonAncestor(currNode.right, p, q)
25+
26+
if (lVal !== null && rVal !== null) return currNode
27+
if (lVal === null && rVal === null) return null
28+
29+
return lVal || rVal
30+
};

0 commit comments

Comments
 (0)