We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent e26874d commit e40abc4Copy full SHA for e40abc4
Lowest Common Ancestor of a Binary Tree/code.js
@@ -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