Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
The lowest common ancestor is defined between two nodes p
and q
as the lowest node in T
that has both p
and q
as descendants (where we allow a node to be a descendant of itself).
Example 1:
Consider the following binary tree:
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
If p
is node 5 and q
is node 1, what is their LCA? Justify your answer.
Example 2:
Using the same tree as above, if p
is node 5 and q
is node 4, what is their LCA? Explain why.
Constraints:
[2, 10^5]
.-10^9 <= Node.val <= 10^9
Node.val
are unique.p != q
p
and q
will exist in the tree.Describe an algorithm to find the LCA efficiently. What is the time and space complexity of your approach? Can you provide code for your solution?
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
One straightforward but inefficient approach is to traverse the tree to find the paths from the root to both nodes p
and q
. Once these paths are found, we can compare them from the root down until the paths diverge. The last common node in both paths is the LCA.
p
and q
.A more efficient solution utilizes recursion. The idea is as follows:
p
or q
, return the root.p
and q
in the left and right subtrees.p
and q
are found in different subtrees. Therefore, the current root is the LCA.p
and q
are in that subtree. Return the non-null node.p
or q
is the root, the root is the LCA.p
or q
do not exist in the tree, the algorithm will still return a node, but it might not be a valid LCA. The problem statement guarantees that both p
and q
will exist.class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root;
}
return (left != null) ? left : right;
}
}