Den Roman’s link (Archived version) seems promising, but it seemed a little bit complicated to me, so I tried another approach. Here is a simple algorithm I used:
Let say you want to compute LCA(x,y) with x and y two nodes.
Each node must have a value color
and count
, resp. initialized to white and 0.
- Color all ancestors of x as blue (can be done using BFS)
- Color all blue ancestors of y as red (BFS again)
- For each red node in the graph, increment its parents’
count
by one
Each red node having a count
value set to 0 is a solution.
There can be more than one solution, depending on your graph. For instance, consider this graph:
LCA(4,5) possible solutions are 1 and 2.
Note it still work if you want find the LCA of 3 nodes or more, you just need to add a different color for each of them.