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).”
Example 1:
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.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Example 3:
Input: root = [1,2], p = 1, q = 2 Output: 1
Constraints:
[2, 105].-109 <= Node.val <= 109Node.val are unique.p != qp and q will exist in the tree.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are trying to find the closest shared meeting point for two people in a massive family tree. The brute force approach involves looking at every single person in the tree one by one to see which ones are related to both targets.
Here's how the algorithm would work step-by-step:
def lowest_common_ancestor(root_node, target_one, target_two):
# We traverse every node to evaluate each one as a potential ancestor candidate
all_tree_nodes = []
def collect_nodes(current_node):
if current_node:
all_tree_nodes.append(current_node)
collect_nodes(current_node.left)
collect_nodes(current_node.right)
collect_nodes(root_node)
def covers_targets(ancestor_node, node_one, node_two):
if not ancestor_node:
return False
def contains_node(subtree_root, target_node):
if not subtree_root:
return False
if subtree_root == target_node:
return True
return contains_node(subtree_root.left, target_node) or contains_node(subtree_root.right, target_node)
return contains_node(ancestor_node, node_one) and contains_node(ancestor_node, node_two)
# We track valid ancestors to find the deepest one among all qualified candidates
valid_ancestors = []
for candidate_node in all_tree_nodes:
if covers_targets(candidate_node, target_one, target_two):
valid_ancestors.append(candidate_node)
def get_node_depth(current_root, target_node, current_depth):
if not current_root:
return -1
if current_root == target_node:
return current_depth
left_search_depth = get_node_depth(current_root.left, target_node, current_depth + 1)
if left_search_depth != -1:
return left_search_depth
return get_node_depth(current_root.right, target_node, current_depth + 1)
deepest_ancestor_node = None
maximum_depth_value = -1
# We compare depths to ensure we select the lowest common ancestor in the tree
for valid_candidate in valid_ancestors:
candidate_depth = get_node_depth(root_node, valid_candidate, 0)
if candidate_depth > maximum_depth_value:
maximum_depth_value = candidate_depth
deepest_ancestor_node = valid_candidate
return deepest_ancestor_nodeTo find the lowest common ancestor in a family tree of nodes, we can dive deep down to the bottom and let each branch report back what it discovers. By asking our children if they have spotted either of our target nodes, we can magically figure out the meeting point on the way back up.
Here's how the algorithm would work step-by-step:
class Solution:
def lowestCommonAncestor(self, root_node, target_node_p, target_node_q):
# Base case: if we hit a dead end or find a target, report this node upward immediately.
if root_node is None or root_node == target_node_p or root_node == target_node_q:
return root_node
left_branch_result = self.lowestCommonAncestor(root_node.left, target_node_p, target_node_q)
right_branch_result = self.lowestCommonAncestor(root_node.right, target_node_p, target_node_q)
# If both sides found something, this current node is the convergence point and LCA.
if left_branch_result and right_branch_result:
return root_node
# If only one side found a target, pass that finding upward along the chain.
return left_branch_result if left_branch_result else right_branch_result| Case | How to Handle |
|---|---|
| One target node is an ancestor of the other target node | The recursive function naturally returns the ancestor node as soon as it hits it without searching further down. |
| The binary tree is completely skewed like a linked list | The recursion depth will equal the height of the tree, reaching up to O(N) frames on the call stack. |
| The tree consists of only a single node | The base case will immediately return that single node if it matches one of the targets. |
| Both target nodes are located in the same subtree of the root | The root will receive non-null returns from only one side, propagating that side's result all the way up. |
| The tree has maximum nodes with a balanced depth of log N | The recursive approach efficiently traverses the tree in O(N) time and O(log N) space due to balanced stack depth. |
| One or both target nodes do not exist in the tree | While standard problems guarantee existence, a robust check ensures we return null if a target is missing. |