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.

If root matches with any of the given nodes (n1, n2) then return root as LCA.

IF not then make recursive callas to left subtree and right subtree for the search of the nodes n1 and n2.

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.

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.

If both the nodes (n1 and n2) will be in the left subtree of the current visiting node then go left

If both the nodes (n1 and n2) will be in the right subtree of the current visiting node then go right.

See Picture for better explanation

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.
__________________________________________________