# Lowest Common Ancestor in a Binary Tree (Not Binary Search Tree).

Objective: Find the Lowest Common Ancestor of two given nodes in a Binary Tree

What is Lowest Common Ancestor

In a given binary tree, The lowest common ancestor of two nodes n1 and n2 will be a node X such that node X will be the lowest node who has n1 and n2 as its descendants.

Similar Problem: Lowest Common Ancestor in a Binary Search Tree.

Example:

Lowest-Common-Ancestor-Example

Input: A binary Tree and two nodes n1 and n2.

Appraoch:

1. Start will the root.
2. If root matches with any of the given nodes (n1, n2) then return root as LCA.
3. IF not then make recursive callas to left subtree and right subtree for the search of the nodes n1 and n2.
4. Now both the nodes (n1 and n2) will be in the left subtree of the current visiting node OR it will be in the right subtree of current visiting OR n1 and n2 will be in each side of current visiting node.
5. If you find a node which has one node in its left subtree and one node in its right subtree than this node will be our lowest common ancestor.
6. If both the nodes (n1 and n2) will be in the left subtree of the current visiting node then go left
7. If both the nodes (n1 and n2) will be in the right subtree of the current visiting node then go right.
8. See Picture for better explanation

LCA-in-Binary-Tree

Complete Code:

Output:

```Lowest Common Ancestor (8, 30 ) is 2
Lowest Common Ancestor (30, 5 ) is 5
```

__________________________________________________
Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

#### You may also like...

• Subha Velayutham

This code does not work when one of the nodes (n1 or n2) does not exist in the tree.

• Anil Singh

The LCA for 5 and 7 is returning as 1 while it should be 5. The code does not handle the case when both the nodes are lies in the same subtree.