Skip to content

Instantly share code, notes, and snippets.

@jleeothon
Last active January 7, 2020 21:45
Show Gist options
  • Save jleeothon/3b30fb21a4e2820ebfc1 to your computer and use it in GitHub Desktop.
Save jleeothon/3b30fb21a4e2820ebfc1 to your computer and use it in GitHub Desktop.
Prolog: lowest common ancestor (LCA)
ancestor(A, B) :- parent(A, B).
ancestor(A, B) :- parent(X, B), ancestor(A, X).
lca(A, B, X) :- ancestor(X, A), ancestor(X, B).
@jleeothon
Copy link
Author

Try with this tree:

parent(a, b).
parent(a, c).
parent(b, d).
parent(b, e).
parent(c, f).
parent(c, g).
parent(d, h).
parent(d, i).
parent(d, j).
parent(e, k).
parent(f, l).
parent(f, m).
parent(g, n).
parent(g, o).
parent(g, p).
parent(g, q).
parent(k, r).
parent(k, s).
parent(m, t).
parent(m, u).
parent(m, v).
parent(o, w).
parent(p, x).
parent(x, y).
parent(x, z).

@DaniGuardiola
Copy link

This won't give you the lowest common ancestor, but the complete list of common ancestors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment