Ben benzer sorular önceden sorulmuş biliyorum ama benim çözüm çok basit olduğunu düşünüyorum. Özellikle kıyasla Vikipedi .
Beni yanlış kanıtlamak Lütfen!
Verilen veri yapısına sahip düğümlerle bir ağaç varsa:
struct node
{
node * left;
node * right;
node * parent;
int key;
}
Böyle bir fonksiyon yazabiliriz:
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;
}
Bu kod oldukça basittir ve en kötü durum O (n), ortalama vaka da (n ağacında düğüm sayısı olduğu) ağaç dengeli, özellikle eğer muhtemelen O (logn) olmasıdır.













