Similar Problem:
- 235. Lowest Common Ancestor of a Binary Search Tree
- 1644. Lowest Common Ancestor of a Binary Tree II
- 1650. Lowest Common Ancestor of a Binary Tree III
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “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).”
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Recursive:
- Base Case:
- if reaches the null nodes, return null
- if find the node p or q, return root
Then,
- Traverse left and right until finds a path containing p or q
- if found a path contains p or q, return root back up to the ancestor
- when returned back up, check for the path at current node (it might be the ancestor of p and q)
- there are 4 cases
- p and q found -> means already found the lowest common ancestor (the first time this condition is true, it's the LCA since it's a bottom-up process)
- p and q not found both null -> not been found yet
- p found and q = null
- p = null and q found -> these two cases, it might be 2 situation, one is a descendant of the other or we haven't see the lowest common ancestor yet so we have to return the found node back up.
Time: O(n)
Space: O(n)
Recursive
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// base case
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 both p and q are found, it's lowest common ancestor
if (left != null && right != null)
return root;
// if either are not found, haven't found a path to p or q
if (left == null && right == null)
return null;
// either one is found or there is impossible that one is not in the subtree of another
return left == null ? right : left;
}