Skip to content

Instantly share code, notes, and snippets.

@bluesunxu
Created December 18, 2012 05:16
Show Gist options
  • Save bluesunxu/4325263 to your computer and use it in GitHub Desktop.
Save bluesunxu/4325263 to your computer and use it in GitHub Desktop.
Find the Lowest Common Ancestor in a Binary Search Tree
node* LCA_BST(node* root, node* c1, node* c2) {
if(!c1 || !c2)
return NULL;
node* cur = root;
while(cur) { // returns NULL if root is NULL
// cur key larger than both keys, LCA in the left subtree
if(cur->key > c1->key && cur->key > c2->key)
cur = cur->left;
// cur key smaller than both keys, LCA in the right subtree
else if(cur->key < c1->key && cur->key < c2->key)
cur = cur->right;
else
// cur key is large than one key and smaller than the other
// or cur key is equal to one of the keys
// LCA is the cur node, break out the loop
break;
}
return cur;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment