I know that similar questions have been asked before, but I think my solution is much simpler. Especially compared to Wikipedia .
Please prove that I'm wrong!
If you have a tree with nodes that have a given data structure:
struct node
{
node * left;
node * right;
node * parent;
int key;
}
You can write a function like this:
node* LCA(node* m, node* n)
{
node* left = null;
node* right = null;
if (m->key < n->key)
{
left = m;
right = n;
}
else
{
left = n;
right = m;
}
while (left->parent && left->parent->key < right->key)
{
left = left->parent;
}
return left;
}
This code is pretty simple, and the worst case is O (n), the middle case is probably O (logn), especially if the tree is balanced (where n is the number of nodes in the tree).
source
share