Find Lowest Common Ancestor

Problem Explanation

The Lowest Common Ancestor (LCA) of two nodes in a binary tree is the deepest (lowest) node that has both nodes as descendants. In other words, it is the lowest node in the tree that is an ancestor of both given nodes.

Approach Name: Recursive

Approach to Solve the Problem

To find the LCA, we can use a recursive approach:

  1. Base Case: If the current node is null, return null. If the current node is one of the two nodes, return the current node.
  2. Recursive Case: Recursively find the LCA in the left and right subtrees.
  3. Combining Results: If both left and right recursive calls return non-null values, the current node is the LCA. If only one returns a non-null value, return the non-null value.
Output:
LCA(5, 21): 20
LCA(10, 32): 25
LCA(21, 32): 25