Skip to content

Instantly share code, notes, and snippets.

@rahulkmr
Created February 7, 2010 07:34
Show Gist options
  • Save rahulkmr/297285 to your computer and use it in GitHub Desktop.
Save rahulkmr/297285 to your computer and use it in GitHub Desktop.
struct node
{
int info;
struct node *left;
struct node *right;
};
struct node *common_ancestor(struct node *head, struct node* n1,
struct node *n2)
{
return common_helper(head, n1, n2, NULL);
}
struct node *common_helper(struct node *head, struct node *n1,
struct node *n2, struct node *parent)
{
if (head == NULL)
return NULL;
else if ((n1->info > head->info && n2->info < head->info) ||
(n1->info < head->info && n2->info > head->info))
return head;
else if (n1->info < head->info && n2->info < head->info) {
return common_ancestor(head->left, n1, n2, head);
}
else if (n1->info > head->info && n2->info > head->info) {
return common_ancestor(head>right, n1, n2, head);
}
else {
return parent;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment