Interface LowestCommonAncestorStatic


  • public interface LowestCommonAncestorStatic
    Static Lowest Common Ancestor (LCA) algorithm.

    The lowest common ancestor of two vertices in a tree is the vertex that appear in both vertices paths to the root (common ancestor), and its farthest from the root (lowest). Given a tree \(G=(V,E)\), we would like to pre process it and then answer queries of the type "what is the lower common ancestor of two vertices \(u\) and \(v\)?".

    Most implementations of this interface achieve linear or near linear preprocessing time and constant or logarithmic query time.

    Use newInstance() to get a default implementation of this interface. A builder obtained via newBuilder() may support different options to obtain different implementations.

     
     Graph<String, Integer> tree = Graph.newUndirected();
     tree.addVertex("Grandfather Bob");
     tree.addVertex("Father John");
     tree.addVertex("Me");
     tree.addVertex("Sister Jane");
     tree.addVertex("Uncle Nick");
     tree.addVertex("Cousin Alice");
    
     tree.addEdge("Grandfather Bob", "Father John", 1957);
     tree.addEdge("Father John", "Me", 1985);
     tree.addEdge("Father John", "Sister Jane", 1987);
     tree.addEdge("Grandfather Bob", "Uncle Nick", 1960);
     tree.addEdge("Uncle Nick", "Cousin Alice", 1990);
    
     LowestCommonAncestorStatic lca = LowestCommonAncestorStatic.newInstance();
     LowestCommonAncestorStatic.DataStructure<String, Integer> lcaDS = lca.preProcessTree(tree, "Grandfather Bob");
     assert lcaDS.findLowestCommonAncestor("Father John", "Uncle Nick").equals("Grandfather Bob");
     assert lcaDS.findLowestCommonAncestor("Me", "Sister Jane").equals("Father John");
     assert lcaDS.findLowestCommonAncestor("Uncle Nick", "Cousin Alice").equals("Uncle Nick");
     assert lcaDS.findLowestCommonAncestor("Me", "Cousin Alice").equals("Grandfather Bob");
     
    Author:
    Barak Ugav
    See Also:
    LowestCommonAncestorDynamic, LowestCommonAncestorOffline