Find Lowest Common Ancestor in Binary Tree

Question:-You have a Binary Tree and Two node p , q.
You have to find the first common parent of p and q. 


tree_node_type *LowestCommonAncestor(
tree_node_type *root , tree_node_type *p , tree_node_type *q)
{
	tree_node_type *l , *r , *temp;
	if(root==NULL)
	{
		return NULL;
	}

	if(root->left==p || root->left==q || root->right ==p || root->right ==q)
	{
		return root;
	}
	else
	{
		l=LowestCommonAncestor(root->left , p , q);
		r=LowestCommonAncestor(root->right , p, q);

		if(l!=NULL && r!=NULL)
		{
			return root;
		}
		else
		{
			temp = (l!=NULL)?l:r;
			return temp;
		}
	}
}

Author: Gour Ch. Saha
Contact for any query:: gour_ch_saha@yahoo.co.in
Free Web Hosting