Wiem, że podobne pytania zostały poproszone wcześniej, ale myślę, że moje rozwiązanie jest znacznie prostsze. Zwłaszcza w porównaniu do Wikipedii .
Proszę udowodnić mi źle!
Jeśli masz drzewo z węzłów, które mają daną strukturę danych:
struct node
{
node * left;
node * right;
node * parent;
int key;
}
Można napisać funkcję tak:
node* LCA(node* m, node* n)
{
// determine which of the nodes is the leftmost
node* left = null;
node* right = null;
if (m->key < n->key)
{
left = m;
right = n;
}
else
{
left = n;
right = m;
}
// start at the leftmost of the two nodes,
// keep moving up the tree until the parent is greater than the right key
while (left->parent && left->parent->key < right->key)
{
left = left->parent;
}
return left;
}
Kod ten jest dość prosty i najgorszy przypadek jest O (n), przeciętny przypadek to chyba O (logn), zwłaszcza jeśli drzewo jest zrównoważony (gdzie n to liczba węzłów w drzewie).













