The pseudocode below determines the lowest common ancestor of each pair in P, given the root r of a tree in which the children of node n are in the set n.children. For this offline algorithm, the set P must be specified in advance. It uses the MakeSet, Find, and Union functions of a disjoint-set data structure. MakeSet(u) removes u to a singleton set, Find(u) returns the standard representative of the set containing u, and Union(u,v) merges the set containing u with the set containing v. TarjanOLCA(r) is first called on the root r.
Each node is initially white, and is colored black after it and all its children have been visited.
For each node pair {u,v} to be investigated:
For reference, here are optimized versions of MakeSet, Find, and Union for a disjoint-set forest:
It is possible to preprocess the input LCA queries in such a manner, that the algorithm works faster by an order of magnitude.
The idea in the optimization is associating nodes with their counterparts in the list of input queries.