VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lowest-common-ancestor-binary-tree-set-1/

⇱ Lowest Common Ancestor in a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lowest Common Ancestor in a Binary Tree

Last Updated : 21 Jan, 2026

Given the root of a Binary Tree with unique values and two node values n1 and n2, find the Lowest Common Ancestor (LCA). LCA is the deepest node that has both n1 and n2 as descendants.

Note: Both node values are always present in the Binary Tree.

Examples:

Input: n1 .data= 4, n2.data = 5

👁 420046698

Output: 2
Explanation: As shown below, LCA of 4 and 5 is 2.

👁 420046699

Input: n1.data = 7, n2.data = 8

👁 10

Output: 3
Explanation: As shown below, LCA of 7 and 8 is 3.

👁 420046724

[Naive Approach] Checking if each node is LCA - O(N^2) Time and O(h) space

The idea is to traverse the tree from root node, and for every node check if it is the LCA.
A node is the LCA if its left subtree has one target node and right subtree has the other target node.


Output
3

[Better Approach] Storing Paths of Nodes from Root - O(n) Time and O(n) Space

The idea is to store the paths to the target nodes from the root in two separate arrays. Then start traversing from the 0th index and look simultaneously into the values stored in the arrays, the LCA is the last matching element in both the arrays.

👁 420046724

Path from root to 7 = 1 -> 3-> 7
Path from root to 8 = 1 -> 3 -> 6 -> 8

  • We start checking from 0th index. As both of the values match, we move to the next index.
  • Now check for values at 1st index, they are also matching, so we move to the 2nd index.
  • Now, we check for 3rd index, there's a mismatch so we consider the previous value. 
  • Therefore, the LCA of (7, 8) is 3.

Output
3

[Expected Approach] Using Single Traversal

In this approach, we start with the root node and recursively searches for the given nodes n1 and n2. If the current root is null, it returns null. If the root matches either of the keys, it returns the root as a potential LCA. Then, it recursively checks the left and right subtrees. If both the left and right recursive calls return non-null values, it means one key is in the left subtree and the other is in the right subtree, so the current root is the LCA. If only one subtree contains the keys, the recursive call returns the non-null subtree result as the LCA.


Output
3

Time Complexity: O(n)
Auxiliary Space: O(h), where h is the height of the tree.

Comment