Skip to main content

236. Lowest Common Ancestor of a Binary Tree

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree

Python

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
# Leaf, but target not found
return None

if root.val == p.val or root.val == q.val:
# Hit the target, current root is p or q
return root

left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)

if not left or not right:
# One or more target are not yet reach
return left if left else right

# Both left and right are reaching the targets, current node is the answer
return root

Javascript

var lowestCommonAncestor = function(root, p, q) {
let res;

const recursive = (node) => {
if (node === null) return false;

const isLeftMatched = recursive(node.left);
const isRightMatched = recursive(node.right);

const isMidMatched = node.val === p.val || node.val === q.val;

if ((isLeftMatched && isRightMatched) || (isLeftMatched && isMidMatched) || (isRightMatched && isMidMatched)) res = node;

return isLeftMatched || isRightMatched || isMidMatched;
}

recursive(root);
return res;
};