Back to DSA
Lowest Common Ancestor of a Binary Tree
mediumIn a binary tree (not necessarily a BST), find the lowest common ancestor of two specified nodes. The lowest common ancestor is the deepest node that is an ancestor of both target nodes. A node is considered an ancestor of itself.
Examples
Example 1:
Input:
root = [10,5,15,3,7,12,20], p = 3, q = 7Output:
5 Example 2:
Input:
root = [10,5,15,3,7,12,20], p = 5, q = 20Output:
10Hints
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || 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;
}
}Time complexity
O(n)Space complexity
O(h)