我知道以前有类似的问题,但我认为我的解决方案要简单得多。特别是与Wikipedia相比。有没有更好的方法找到最低的共同祖先?
请证明我的看法!
如果你有一个包含了给定数据结构的节点树:
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是树中节点的数量)。
感谢您的解释! – theninjagreg 2012-07-10 07:07:43