How can I compute the lowest common ancestor (LCA) for a directed graph in networkx
for a subset of vertices?
For example, for the graph
G = nx.DiGraph()
G.add_edges_from([(1, 2), (1, 3), (3, 4), (3, 5)])
vertex 3
is the LCA for the vertex {4, 5}
and vertex 1
for the the nodes {3, 4, 5}
. In case it matters: All vertices are leaves.
nx.lowest_common_ancestor()
is not suitable since it requires a pair of vertices, but does not allow a set of vertices.
Thanks!
After checking the source code of the nx.lowest_common_ancestor, I found the function for calculating the LCA with a pair of 2 nodes.
So I did some modifications for this code can work for multiple nodes and return to node
1
not node3
when the input nodes are{3, 4, 5}
.Here shows the result of the codes :