Lowest Common Ancestor of a Binary Tree
Pattern: Lowest common ancestor
Recurse: if the node is empty or is p or q, return it. Otherwise ask both subtrees. If both return something, p and q are on different sides and this node is the answer; otherwise pass up whichever side found something.
The problem
Given a tree 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). Values are different. For the example, 5 and 1 give 3, and 5 and
4 give 5. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- If p is in the left subtree and q in the right, where do they meet?
- What if both are on one side?
- What if the node itself is p?
Hints
Brute force, and why it fails
Record both root-to-node paths and find where they split: O(n) too, but two passes and extra lists.
The key insight
Each call reports whether it found p, q or their meeting point, so one post-order pass finds the split.
Dry run
Tree [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 1. At 3: ask left.
The plan
lca(n): if n is null or n is p or n is q: return n
l = lca(left); r = lca(right)
if l and r: return n
return l or r
Complexity
- Time
O(n)- Space
O(h)
One pass.
Edge cases
- p is an ancestor of q: p.
- p and q are siblings: their parent.
- p equals q: p.
I've built my logic, show the code
Java
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root; // found one of them (or nothing)
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) return root; // one on each side: this is where they meet
return left != null ? left : right; // both on one side: pass that answer up
}
}C++
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL || root == p || root == q) return root; // found one of them (or nothing)
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != NULL && right != NULL) return root; // one on each side: this is where they meet
return left != NULL ? left : right; // both on one side: pass that answer up
}
};Python
class Solution:
def lowestCommonAncestor(self, root, p, q):
if root is None or root is p or root is q:
return root # found one of them (or nothing)
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root # one on each side: this is where they meet
return left or right # both on one side: pass that answer upCommon mistakes
- Comparing values when they can repeat.
- Returning the root whenever both are present somewhere.