我知道之前有类似的问题,但我认为我的解决方案要简单得多。特别是与维基百科相比。
请证明我错了!
如果您有一棵树,其节点具有给定的数据结构:
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;
}
这段代码非常简单,最坏情况下的时间复杂度为O(n),平均情况下可能是O(logn),特别是如果树是平衡的(其中n是树中节点的数量)。