Imagine a directed acyclic graph as follows, where:
- "A" is the root (there is always exactly one root)
- each node knows its parent(s)
- the node names are arbitrary - nothing can be inferred from them
- we know from another source that the nodes were added to the tree in the order A to G (e.g. they are commits in a version control system)
What algorithm could I use to determine the lowest common ancestor (LCA) of two arbitrary nodes, for example, the common ancestor of:
- B and E is B
- D and F is B
Note:
- There is not necessarily a single path to a given node from the root (e.g. "G" has two paths), so you can't simply traverse paths from root to the two nodes and look for the last equal element
- I've found LCA algorithms for trees, especially binary trees, but they do not apply here because a node can have multiple parents (i.e. this is not a tree)