arrow-left

All pages
gitbookPowered by GitBook
1 of 1

Loading...

8.1. Abstraction

This section discusses spanning trees in a graph.

hashtag
Overview

A spanning tree in a graph is a tree that contains all vertices in the graphs as its nodes. A minimum spanning tree is a spanning tree whose sum of all edge weights is the minimum among all the other spanning trees in the graph.

Can a graph have more than one minimum spanning tree?

hashtag
Spanning Tree

Let us define the class under the package:

  • L1: inherits the interface.

  • L2: contains all edges in this spanning tree.

  • L3

We then define getters and setters:

  • L3: the size of the spanning tree is determined by the number of edges.

Finally, we override the compareTo() method that makes the comparison to another spanning tree by the total weight:

hashtag
MST

Let us create the interface that is inherited by all minimum spanning tree algorithms:

  • L2: an abstract method that takes a graph and returns a minimum spanning tree.

: contains the total weight of this spanning tree.
SpanningTreearrow-up-right
graph.spanarrow-up-right
Comparablearrow-up-right
MSTarrow-up-right
public class SpanningTree implements Comparable<SpanningTree> {
    private final List<Edge> edges;
    private double total_weight;

    public SpanningTree() {
        edges = new ArrayList<>();
    }

    public SpanningTree(SpanningTree tree) {
        edges = new ArrayList<>(tree.getEdges());
        total_weight = tree.getTotalWeight();
    }
}
public List<Edge> getEdges() { return edges; }
public double getTotalWeight() { return total_weight; }
public int size() { return edges.size(); }

public void addEdge(Edge edge) {
    edges.add(edge);
    total_weight += edge.getWeight();
}
@Override
public int compareTo(SpanningTree tree) {
    double diff = total_weight - tree.total_weight;
    if (diff > 0) return 1;
    else if (diff < 0) return -1;
    else return 0;
}
public interface MST {
    public SpanningTree getMinimumSpanningTree(Graph graph);
}