Skip to content

Instantly share code, notes, and snippets.

@gabhi
Created April 24, 2014 07:11
Show Gist options
  • Save gabhi/11244538 to your computer and use it in GitHub Desktop.
Save gabhi/11244538 to your computer and use it in GitHub Desktop.
lca lowest common ancestor
struct node *lca(struct node* root, int n1, int n2)
{
if (root == NULL) return NULL;
// If both n1 and n2 are smaller than root, then LCA lies in left
if (root->data > n1 && root->data > n2)
return lca(root->left, n1, n2);
// If both n1 and n2 are greater than root, then LCA lies in right
if (root->data < n1 && root->data < n2)
return lca(root->right, n1, n2);
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment