Suppose we have a tree in igraph
:
library(igraph)
g <- make_tree(14, children = 3)
plot(g, layout = layout_as_tree)
Created on 2019-12-21 by the reprex package (v0.3.0)
How do we find the lowest common ancestor (LCA) of an arbitrary collection of nodes? That is, in the above example
- The LCA of 7 and 14 is 2.
- The LCA of 6, 9, 12, and 14 is 1.
- The LCA of 1 and 8 is 1.
- The LCA of any node is itself.
And so on.
It feels like there ought to be an elegant way of doing this in igraph
, but I haven't managed to find it. I played around with intersections of calls to all_simple_paths
, but since I don't have a good way to get the levels of each node, this didn't help.
I am aware that many of the phylogenetics packages implement this for other data structures, but I would rather avoid the interconversion if there is a reasonable solution on the graph. (I'm perfectly happy with a tidygraph
solution, however.)