AlgoMaster Logo

Lowest Common Ancestor of a Binary Tree

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Traversal with Multiple Returns

Intuition:

This approach involves recursively traversing the binary tree from the root node and returning the lowest common ancestor. The idea is to essentially perform a post-order traversal of the tree while returning conditions that help conclude the LCA.

  1. If the current node is one of the target nodes p or q, we return this node as a candidate for the LCA.
  2. Recursively search both left and right subtrees for the target nodes p and q.
  3. If both left and right subtree calls return a non-null value, it means p and q are found in different subtrees of the current node, making the current node the LCA.
  4. If only one of the subtree calls returns a non-null value, this means both nodes are located in that subtree, and we return that value upward.

Code:

2. Iterative using Parent Pointers

Intuition:

In this approach, we utilize a parent pointer for all nodes starting from the root. Once we have parent pointers, we can track the path from each node p and q to the root. The first common node in these two paths is the LCA.

  1. Use a hashmap to store the parent of each node.
  2. Traverse the tree to populate the parent pointers.
  3. Track back from node p to the root and save all visited ancestors in a set.
  4. Track back from node q and find the first common ancestor in the set.

Code:

3. Optimized Recursive Traversal

Intuition:

This approach is a refined version of the first recursive approach. It involves a single recursive post-order traversal to find the LCA more clearly and concisely.

  1. If the current node is null, return null, indicating that neither p nor q is found below.
  2. If the current node is equal to p or q, return the current node.
  3. Otherwise, recursively call on the left and right subtrees.
  4. If both left and right calls return non-null, the current node is the LCA.
  5. Otherwise, return the non-null value from left or right.

Code: