views:

383

answers:

1

I know similar questions have been asked before, but I think my solution is far simpler. Especially compared to [http://en.wikipedia.org/wiki/Tarjan's_off-line_least_common_ancestors_algorithm].

Please prove me wrong!

If you have a tree with nodes that have the given data structure:

struct node
{
    node * left;
    node * right;
    node * parent;
    int key;
}

You could write a function like this:

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;
}

This code is pretty straightforward and worst case is O(n), average case it is probably O(logn), especially if the tree is balanced (where n is the number of nodes in the tree).