236. Lowest Common Ancestor of a Binary Tree
Asked at 21Meta87Amazon70Apple61Microsoft53Bloomberg45Google42BlackRock60Airwallex100Wix87Atlassian76Adobe69Lucid69BitGo68LinkedIn63SAP62Yandex55TikTok53Oracle52Cisco45Intuit43Goldman Sachs21
Problem
Given a binary tree (not a BST) and two of its nodes p and q, return their lowest common ancestor: the deepest node that has both as descendants (a node counts as its own descendant).
Example: [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 → 3; p = 5, q = 4 → 5
Constraints: up to 10⁵ nodes; values are unique.
DFS returns p or q if found in the subtree (else null). If both sides return non-null, the current node is the LCA; otherwise bubble up whichever side is non-null.
Complexity: O(n).
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or root is p or root is q:
return root
l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p, q)
return root if l and r else l or r
t = make_tree([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4])
assert Solution().lowestCommonAncestor(t, find_node(t, 5), find_node(t, 1)).val == 3
assert Solution().lowestCommonAncestor(t, find_node(t, 5), find_node(t, 4)).val == 5
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode l = lowestCommonAncestor(root.left, p, q), r = lowestCommonAncestor(root.right, p, q);
if (l != null && r != null) return root;
return l != null ? l : r;
}
}
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil || root == p || root == q {
return root
}
l := lowestCommonAncestor(root.Left, p, q)
r := lowestCommonAncestor(root.Right, p, q)
if l != nil && r != nil { // one on each side
return root
}
if l != nil {
return l
}
return r
}