Skip to content

Commit 9dad5df

Browse files
authored
Update 1644-lowest-common-ancestor-of-a-binary-tree-ii.js
1 parent 9d9ad5b commit 9dad5df

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

1644-lowest-common-ancestor-of-a-binary-tree-ii.js

+38
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,41 @@ const lowestCommonAncestor = function (root, p, q) {
3333
dfs(root)
3434
return cn
3535
}
36+
37+
// another
38+
39+
/**
40+
* Definition for a binary tree node.
41+
* function TreeNode(val) {
42+
* this.val = val;
43+
* this.left = this.right = null;
44+
* }
45+
*/
46+
/**
47+
* @param {TreeNode} root
48+
* @param {TreeNode} p
49+
* @param {TreeNode} q
50+
* @return {TreeNode}
51+
*/
52+
const lowestCommonAncestor = function (root, p, q) {
53+
let hasP = false, hasQ = false
54+
const res = LCA(root, p, q)
55+
return hasP && hasQ ? res : null
56+
57+
function LCA(root, p, q) {
58+
if(root == null) return root
59+
const left = LCA(root.left, p, q)
60+
const right = LCA(root.right, p, q)
61+
if(root === p) {
62+
hasP = true
63+
return root
64+
}
65+
if(root === q) {
66+
hasQ = true
67+
return root
68+
}
69+
if(left && right) return root
70+
return left || right
71+
}
72+
}
73+

0 commit comments

Comments
 (0)