# Lowest Common Ancestor(LCA) in Binary Tree

Following is definition of LCA from Wikipedia:
Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself).

Thus lca is guaranteed to exist if both the nodes are present in tree.  In any other case it is NULL. LCA of 4 and 5 is 3.
LCA of 2 and 5 is 1.
LCA of 3 and 5 is 3.

Traverse the tree from bottom, and if node value matches any of two nodes, we pass that to its parent, parent would now check it’s left and right subtree,if it finds, node in each one of them , then parent is the LCA and we pass it to its parent up to the root. if not, we pass the lower node which contains either one of the two nodes (if the left or right subtree contains either n1 or n2), or NULL (left and right subparts do not contain either of n1 & n2) up.

Readers are requested to submit their codes in different languages and using different ways in comment section below. Also it is advised to try it yourself before looking at the solution .

The overall time complexity of this approach is O(n).

Code:-

[code language=”cpp”]

#include<bits/stdc++.h>

struct Treenode// definition of structure of tree node which has lchild child and rchild child
{
int val;
Treenode* lchild;
Treenode* rchild;
};

struct Treenode* newNode(int key)// function for new node creation
{ /* dynamically allocate memory for a new node */
struct Treenode* newnode = (struct Treenode*)malloc(sizeof(struct Treenode));
newnode->val = key;
newnode->lchild = NULL;
newnode->rchild = NULL;

return(newnode);
}

struct Treenode *findLCA(struct Treenode* root, int node1, int node2)
{
// Base case
if (!root) return NULL;

// if root value equals any of two nodes data then lca is root.
if (root->val == node1 || root->val == node2)
return root;

// otherwise we need to look in left pr right parts
Treenode *ls = findLCA(root->lchild, node1, node2);
Treenode *rs= findLCA(root->rchild, node1, node2);

if (ls && rs) return root;

// check if left subtree or right subtree is LCA
return (ls != NULL)? ls: rs;
}

int main()
{
Treenode *root1 = newNode(232);
Treenode *root2 = newNode(232);// these part is concerned with creation of tree
// user can edit this as per wish
root1->lchild = newNode(231);
root1->rchild = newNode(231);
root1->lchild->lchild = newNode(431);
root1->lchild->rchild = newNode(531);

root2->lchild = newNode(231);
root2->rchild = newNode(331);
root2->lchild->lchild = newNode(431);
root2->lchild->rchild = newNode(513);

cout<<LCA(root)<<endl;

getchar();
return 0;
}

[/code]