मैं जानता हूँ कि इसी तरह के सवाल से पहले कहा गया है, लेकिन मुझे लगता है कि मेरी समाधान बहुत आसान है। विशेष रूप से की तुलना में विकिपीडिया ।
कृपया मुझे गलत साबित!
आप नोड्स दिए गए डेटा संरचना है कि के साथ एक पेड़ है, तो:
struct node
{
node * left;
node * right;
node * parent;
int key;
}
आप इस प्रकार का समारोह लिख सकते हैं:
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;
}
इस कोड को बिल्कुल स्पष्ट है और सबसे ज्यादा मामले हे (एन), औसत मामला यह शायद ओ (logn), खासकर अगर पेड़ संतुलित किया जाता है (जहां n पेड़ में नोड्स की संख्या है) है।













