Lowest Common Ancestor of a Binary Tree
Descrition
doc
Solutions
First Idea
function oneOf(p, q, ref) {
return ref.val === p.val || ref.val === q.val
}
function identical(p, q, left, right) {
return (
(left?.val === p.val && right?.val === q.val) ||
(left?.val === q.val && right?.val === p.val)
)
}
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function (root, p, q) {
if (!root) {
return null
}
const left = lowestCommonAncestor(root.left, p, q)
const right = lowestCommonAncestor(root.right, p, q)
if (identical(p, q, left, right) || oneOf(p, q, root)) {
return root
}
return left !== null ? left : right
}
- Time Complexity: O(n)
- Space Complexity: O(1)