Spanning Tree vs Minimum Spanning Tree: Examples & Algorithms

Data Structure / Graph Algorithms Chapter 54

Spanning Tree vs Minimum Spanning Tree: Examples & Algorithms

Learn Spanning Tree and Minimum Spanning Tree with simple weighted graph examples, pictorial diagrams, Prim's and Kruskal's algorithms, C programs and time complexity.

Weighted Graph Prim's Algorithm Kruskal's Algorithm C Programs Live MST Lab
Ordinary Spanning Tree 16 units Connects every vertex without cycles.
Minimum Spanning Tree 13 units Lowest total weight in this example.

Imagine that five college buildings need to be connected using network cables.

We can connect these buildings in different ways. But laying extra cables increases the total cost of the network.

Our first goal is simple: all five buildings should be connected.

Our second goal is to make these connections without creating unnecessary cycles.

Our third goal is to spend the minimum possible amount on cable connections.

These three ideas help us understand two important concepts in Data Structure: Spanning Tree and Minimum Spanning Tree.

Many students understand the definition of a Spanning Tree, but become confused when asked why a Minimum Spanning Tree is different, how to calculate its total cost, or how Prim's and Kruskal's algorithms select edges.

In this chapter, we will learn these concepts using the same small weighted graph. We will also see step-by-step dry runs, C programs, comparison tables and an interactive MST visualizer.

Quick Answer: Spanning Tree vs Minimum Spanning Tree

A Spanning Tree is a subgraph of a connected, undirected graph that contains all vertices, remains connected and has no cycle.

A Minimum Spanning Tree (MST) is a Spanning Tree whose total edge weight is the smallest among all possible Spanning Trees of that graph.

Both contain exactly V−1 edges for V vertices. The difference is that an ordinary Spanning Tree does not need to have minimum total weight.

What Is a Spanning Tree in Data Structure?

Spanning Tree vs Minimum Spanning Tree: Examples & Algorithms

A Spanning Tree connects every vertex of a connected, undirected graph without creating a cycle.

The word spanning means that the tree covers all vertices of the original graph.

A Tree is connected and does not contain a cycle.

Therefore, a Spanning Tree must satisfy three important conditions.

Conditions of a Spanning Tree: 1. Include all vertices. 2. Keep all vertices connected. 3. Do not create any cycle.

Simple Example

Suppose a graph contains four vertices: A, B, C and D.

The connections A–B, B–C and C–D form a Spanning Tree.

Original Vertices: A, B, C, D Spanning Tree: A — B — C — D Vertices = 4 Edges = 3

Notice that the Spanning Tree has exactly one fewer edge than the number of vertices.

Exam Memory Trick: A Spanning Tree connects all vertices, contains no cycle and has V−1 edges.

Weighted Graph Example for Spanning Tree and MST

We will use a connected, undirected, weighted graph with five vertices.

The vertices are A, B, C, D and E.

Every edge has a weight representing a cost.

Vertices: V = {A, B, C, D, E} Edges and Weights: AB = 2 AC = 3 BC = 1 BD = 4 CD = 5 CE = 6 DE = 7 Vertices = 5 Edges = 7
Original Weighted Graph

Edge labels show weights. These weights are illustrative cost units.

Edge Weight Table

Edge Weight Meaning
A–B2Cost of connecting A and B
A–C3Cost of connecting A and C
B–C1Cost of connecting B and C
B–D4Cost of connecting B and D
C–D5Cost of connecting C and D
C–E6Cost of connecting C and E
D–E7Cost of connecting D and E

Our job is to select some of these edges so that all five vertices remain connected without creating a cycle.

Spanning Tree Example with Total Weight

Let us select these four edges:

Selected Edges: AB = 2 AC = 3 BD = 4 DE = 7

These edges connect all five vertices.

They do not form any cycle, so they create a valid Spanning Tree.

Calculate Total Weight

Total Weight: = 2 + 3 + 4 + 7 = 16 units

This is a valid Spanning Tree.

But is it the Minimum Spanning Tree?

Not necessarily, because there may be another Spanning Tree with a smaller total weight.

Important: A Spanning Tree does not need to have the smallest possible total weight.

What Is Minimum Spanning Tree (MST)?

A Minimum Spanning Tree is a Spanning Tree with the smallest possible sum of edge weights.

It connects all vertices without cycles while keeping the total connection cost as low as possible.

MST Example

For our weighted graph, choose the following edges:

Minimum Spanning Tree Edges: BC = 1 AB = 2 BD = 4 CE = 6

These edges connect A, B, C, D and E, and do not form a cycle.

Total MST Weight

MST Total Weight: = 1 + 2 + 4 + 6 = 13 units

Notice the difference. The ordinary Spanning Tree costs 16 units, while the MST costs 13 units.

Pictorial Comparison of Both Trees

Ordinary Spanning Tree

C 3 A 2 B 4 D 7 E

Valid tree with five vertices and four edges.

Total = 16

Minimum Spanning Tree

A 2 B 1 C 6 E

Vertex D is also connected through edge B–D with weight 4.

Total = 13
Final Difference

Every Minimum Spanning Tree is a Spanning Tree, but not every Spanning Tree is a Minimum Spanning Tree.

Properties of Spanning Tree and Minimum Spanning Tree

1. Exactly V−1 Edges

A Spanning Tree with V vertices always has V−1 edges.

Number of Vertices = V Spanning Tree Edges = V - 1 For V = 5: Edges = 4

2. No Cycles

A Spanning Tree cannot contain a cycle. Adding any extra edge between two existing vertices of the tree creates a cycle.

3. All Vertices Are Connected

Every vertex is reachable from every other vertex through the selected edges.

4. Exactly One Simple Path

In a Tree, there is exactly one simple path between any two vertices.

5. A Graph May Have Multiple Spanning Trees

A connected graph can have different valid Spanning Trees. They may use different edges and have different total weights.

6. MST Has Minimum Total Weight

An MST has the smallest total weight among all possible Spanning Trees.

7. MST May Not Be Unique

If some edges have equal weights, a graph may have more than one Minimum Spanning Tree.

If all edge weights are distinct in a connected undirected graph, its MST is unique.

8. What About Disconnected Graphs?

A disconnected graph cannot have one Spanning Tree that covers all its vertices.

Instead, we can find a Minimum Spanning Forest: a minimum-weight spanning tree for each connected component.

Exam Tip: Never forget the connected-graph condition when defining an MST.

Spanning Tree vs Minimum Spanning Tree: Difference Table

Feature Spanning Tree Minimum Spanning Tree
Meaning Connects all vertices without cycles Spanning Tree with minimum total weight
All Vertices Included Included
Number of Edges V−1 V−1
Cycles Not allowed Not allowed
Minimum Cost Not required Required
Weights Not necessary for the basic concept Needed to compare total weight
Algorithms DFS or BFS can produce a spanning tree Prim's or Kruskal's algorithm
Our Example 16 units 13 units

Remember: Spanning Tree means minimum edges needed to maintain a connected, cycle-free tree. Minimum Spanning Tree additionally minimizes the sum of edge weights.

Prim's Algorithm for Minimum Spanning Tree with Example

Prim's Algorithm is a greedy algorithm used to find a Minimum Spanning Tree.

Greedy means making the best valid local choice at each step.

Prim's Algorithm starts from one vertex and grows a single tree.

At each step, it chooses the minimum-weight edge connecting a vertex already in the tree to a vertex outside the tree.

Prim's Algorithm Steps

  1. Choose a starting vertex.
  2. Mark that vertex as included.
  3. Find the cheapest edge connecting the tree to a new vertex.
  4. Add the edge and its new vertex.
  5. Repeat until all vertices are included.

Prim's Algorithm Dry Run

Start from vertex A in our weighted graph.

Step 1 — Start at A

No edge has been selected yet. The available edges from A are AB(2) and AC(3).

Step 2 — Select AB(2)

AB has lower weight than AC, so choose AB.

Tree vertices: {A, B}.

Step 3 — Select BC(1)

From the current tree, BC(1) is the cheapest edge reaching an unvisited vertex.

Tree vertices: {A, B, C}.

Step 4 — Select BD(4)

The remaining vertices are D and E.

BD(4) is the cheapest valid edge connecting the tree to a new vertex.

Tree vertices: {A, B, C, D}.

Step 5 — Select CE(6)

Only E remains. CE(6) is cheaper than DE(7).

Add CE. All vertices are now connected.

Prim's Algorithm Final Result

Selected Edges: AB = 2 BC = 1 BD = 4 CE = 6 Total MST Weight: 2 + 1 + 4 + 6 = 13

Prim's Algorithm Pseudocode

Prim's Algorithm
Start from a vertex.

Add it to the current tree.

while some vertex is outside the tree:

    Find the cheapest edge

    connecting the current tree

    to an outside vertex.

    Add that edge and vertex.

Return the selected tree.

Memory Trick: Prim's Algorithm grows one tree. It always connects the current tree to one new vertex.

Kruskal's Algorithm for Minimum Spanning Tree with Example

Kruskal's Algorithm is another greedy method for finding a Minimum Spanning Tree.

Unlike Prim's Algorithm, Kruskal's Algorithm does not need to grow one tree from a starting vertex.

It sorts all edges by increasing weight and selects the cheapest valid edges.

An edge is rejected when adding it would create a cycle.

Kruskal's Algorithm Steps

  1. Sort all edges in increasing order of weight.
  2. Begin with every vertex in a separate group.
  3. Choose the next cheapest edge.
  4. Add it if its endpoints are in different groups.
  5. Otherwise, reject it to avoid a cycle.
  6. Stop when V−1 edges are selected.

Step-by-Step Kruskal's Dry Run

Edge Weight Decision Reason
B–C 1 Accept Connects two separate vertices
A–B 2 Accept Adds A to the growing forest
A–C 3 Reject Creates cycle A–B–C–A
B–D 4 Accept Connects D
C–D 5 Reject Creates another cycle
C–E 6 Accept Connects E and completes the MST

We now have four selected edges for five vertices.

Therefore, the MST is complete. There is no need to examine DE(7) afterward.

Kruskal Selected Edges: BC = 1 AB = 2 BD = 4 CE = 6 Total Weight = 13

How Does Kruskal Avoid Cycles?

A common implementation uses a Data Structure called Disjoint Set Union (DSU), also called Union-Find.

DSU checks whether the endpoints of an edge already belong to the same connected group.

If they are already in the same group, adding the edge would create a cycle.

Kruskal's Algorithm Pseudocode

Kruskal's Algorithm
Sort all edges by weight.

Create one set per vertex.

MST = empty

for each edge (u, v):

    if Find(u) != Find(v):

        Add edge to MST

        Union(u, v)

    if MST has V - 1 edges:

        Stop

Return MST.

Memory Trick: Kruskal = Sort edges, accept cheap connections, reject cycles.

Prim's vs Kruskal's Algorithm: Important Differences

Feature Prim's Algorithm Kruskal's Algorithm
Approach Grows one tree Joins separate trees
Starting Vertex Required in common implementations Not required
Edge Selection Cheapest edge leaving current tree Cheapest valid edge globally
Main Structure Matrix or Priority Queue Sorted edges and DSU
Cycle Handling Adds only an outside vertex Rejects edges joining the same set
Typical Use Growing an MST from one vertex Processing edges in sorted order

Both algorithms can produce an MST for a connected, weighted, undirected graph.

In this example, they produce the same four MST edges and total weight 13.

Prim's and Kruskal's Time Complexity

The time complexity depends on which data structures we use to implement these algorithms.

Prim's Algorithm with Adjacency Matrix

We scan vertices to find the cheapest next connection.

Prim with Matrix: Time = O(V²) Graph Storage = O(V²) Extra Working Space = O(V)

Prim's Algorithm with Binary Heap

Using an Adjacency List and suitable Priority Queue can improve performance on sparse graphs.

Prim with Binary Heap: Time = O((V + E) log V) Using Adjacency List and Heap

Kruskal's Algorithm

Kruskal sorts all edges by weight. DSU then helps check whether an edge creates a cycle.

Kruskal with DSU: Time = O(E log E) Main Work: Sorting Edges DSU Additional Space: O(V)

Time Complexity Comparison

Algorithm Implementation Time
Prim Adjacency Matrix O(V²)
Prim Adjacency List + Binary Heap O((V+E) log V)
Kruskal Sorted Edges + DSU O(E log E)

Exam Point: Do not write one time complexity for every version of Prim's Algorithm. Always mention the implementation.

Minimum Spanning Tree Programs in C with Output

Now let us implement both algorithms in C programming.

We will use the same five-vertex weighted graph.

Program 1: Prim's Algorithm in C

This program uses an Adjacency Matrix.

For this example, zero represents an absent edge, and all actual edge weights are positive.

prim.c — Complete C11 Program
#include <stdio.h>
#include <limits.h>

#define V 5

int main(void) {

    int g[V][V] = {

        {0,2,3,0,0},
        {2,0,1,4,0},
        {3,1,0,5,6},
        {0,4,5,0,7},
        {0,0,6,7,0}

    };

    int selected[V] = {0};

    int best[V];
    int parent[V];

    for (int i = 0; i < V; i++) {

        best[i] = INT_MAX;
        parent[i] = -1;
    }

    best[0] = 0;

    int total = 0;
    int count = 0;

    puts("Prim MST (start A):");

    for (int step = 0; step < V; step++) {

        int u = -1;

        for (int i = 0; i < V; i++) {

            if (
                !selected[i] &&
                (
                    u == -1 ||
                    best[i] < best[u]
                )
            ) {
                u = i;
            }
        }

        if (
            u == -1 ||
            best[u] == INT_MAX
        ) {

            puts("Graph is disconnected.");
            return 1;
        }

        selected[u] = 1;

        if (parent[u] != -1) {

            printf(
                "%c-%c : %d\n",
                'A' + parent[u],
                'A' + u,
                best[u]
            );

            total += best[u];
            count++;
        }

        for (int v = 0; v < V; v++) {

            if (
                g[u][v] > 0 &&
                !selected[v] &&
                g[u][v] < best[v]
            ) {

                best[v] = g[u][v];
                parent[v] = u;
            }
        }
    }

    printf(
        "Edges: %d, Total weight: %d\n",
        count,
        total
    );

    return 0;
}

Output of Prim's C Program

Prim's Output
Prim MST (start A):
A-B : 2
B-C : 1
B-D : 4
C-E : 6
Edges: 4, Total weight: 13

Explanation of Prim's C Program

The matrix stores the weighted graph.

The selected array keeps track of vertices already included in the growing tree.

The best array stores the smallest known connection cost from the current tree to each outside vertex.

The parent array remembers which selected vertex provides that connection.

At each step, the program chooses the cheapest available outside vertex.

After selecting all vertices, it displays the MST edges and total weight.

Program 2: Kruskal's Algorithm in C

This program stores edges in an array, sorts them by weight and uses DSU to avoid cycles.

kruskal.c — Complete C11 Program
#include <stdio.h>
#include <stdlib.h>

#define V 5
#define E 7

typedef struct {

    int u;
    int v;
    int w;

} Edge;

static int parent[V];
static int size[V];

static int find(int x) {

    if (parent[x] != x) {

        parent[x] = find(parent[x]);
    }

    return parent[x];
}

static int unite(int a, int b) {

    a = find(a);
    b = find(b);

    if (a == b) {
        return 0;
    }

    if (size[a] < size[b]) {

        int tmp = a;
        a = b;
        b = tmp;
    }

    parent[b] = a;
    size[a] += size[b];

    return 1;
}

static int byWeight(
    const void *a,
    const void *b
) {

    const Edge *x = a;
    const Edge *y = b;

    return
        (x->w > y->w) -
        (x->w < y->w);
}

int main(void) {

    Edge edges[E] = {

        {0,1,2},
        {0,2,3},
        {1,2,1},
        {1,3,4},
        {2,3,5},
        {2,4,6},
        {3,4,7}

    };

    for (int i = 0; i < V; i++) {

        parent[i] = i;
        size[i] = 1;
    }

    qsort(
        edges,
        E,
        sizeof edges[0],
        byWeight
    );

    int count = 0;
    int total = 0;

    puts("Kruskal MST:");

    for (
        int i = 0;
        i < E && count < V-1;
        i++
    ) {

        Edge e = edges[i];

        if (unite(e.u, e.v)) {

            printf(
                "%c-%c : %d\n",
                'A' + e.u,
                'A' + e.v,
                e.w
            );

            total += e.w;
            count++;
        }
    }

    if (count != V-1) {

        puts("Graph is disconnected.");
        return 1;
    }

    printf(
        "Edges: %d, Total weight: %d\n",
        count,
        total
    );

    return 0;
}

Output of Kruskal's C Program

Kruskal's Output
Kruskal MST:
B-C : 1
A-B : 2
B-D : 4
C-E : 6
Edges: 4, Total weight: 13

Explanation of Kruskal's C Program

The program first stores all seven weighted edges.

The qsort function sorts the edges in increasing order of weight.

Every vertex starts in its own DSU group.

The find function identifies a vertex's group representative.

The unite function joins two separate groups. If they already belong to the same group, the edge is rejected.

The algorithm stops after selecting four edges.

How to Run Both Programs in VS Code

Create two files: prim.c and kruskal.c. Paste the corresponding program into each file.

Compile in GCC
gcc -std=c11 -Wall -Wextra prim.c -o prim

gcc -std=c11 -Wall -Wextra kruskal.c -o kruskal
Run in Windows PowerShell
.\prim.exe

.\kruskal.exe

Code Verification: Both programs were compiled with GCC/C11 using warning and strict compilation checks. Both returned four MST edges with total weight 13.

Interactive Prim's and Kruskal's MST Visualizer

Now you can see how both algorithms select edges.

Choose Prim's or Kruskal's algorithm and click Next Step.

The graph highlights the selected edges and calculates the running cost.

MST Blueprint Lab

Same weighted graph. Two greedy algorithms. One minimum total weight.

Live Weighted Graph

Green edges belong to the selected MST. Yellow indicates the current edge decision.

0 / 4 Selected Edges
0 Current MST Weight

Start with no selected edges.

Step 1

Build Your Own Spanning Tree

Select edges yourself. The tool checks cycles, connectivity, selected edge count and total weight.

Try to build a valid Spanning Tree with only four edges. Then see if its total cost is the minimum.

0 Chosen Edges
0 Your Total Weight
Tree Validation

Choose four edges without creating a cycle.

Practice 1: Select AB, AC, BD and DE. You will build a valid Spanning Tree with cost 16.

Practice 2: Clear the selection. Choose BC, AB, BD and CE. The result should be an MST with cost 13.

Practice 3: Choose AB, AC and BC. These edges create a cycle, so the tool should reject the selection as a Spanning Tree.

Applications of Minimum Spanning Tree

1. Computer Network Design

MST can help model the problem of connecting computers or network locations with a minimum total link cost.

2. Electrical Connections

In a simplified model, MST can help choose low-cost connections between electrical locations.

3. Cable and Fibre Networks

Weighted edges can represent installation costs. An MST gives the least total weight under the model's assumptions.

4. Road Network Planning

An MST can help study a minimum-cost network connecting locations.

Real transport projects may require additional routes and reliability, so an MST alone is not always a complete solution.

5. Clustering Algorithms

MSTs are also useful in certain clustering methods, where connections between data points help identify groups.

6. Network Optimization

MST is a useful mathematical model when we want complete connectivity with minimum total connection weight.

Common Mistakes in Spanning Tree and MST

Mistake Correct Concept
Thinking every Spanning Tree has minimum weight Only an MST has minimum total weight.
Choosing V edges A Spanning Tree needs V−1 edges.
Creating cycles A Tree must be cycle-free.
Leaving a vertex disconnected All vertices must be included.
Always choosing the globally cheapest edge in Prim Prim chooses the cheapest edge leaving the current tree.
Ignoring cycles in Kruskal Kruskal rejects edges joining vertices already in the same group.
Assuming an MST must be unique Equal weights can allow multiple MSTs.
Confusing MST with shortest path tree MST minimizes total tree weight, not every path distance from a source.

Important Spanning Tree and MST Questions with Answers

2 MARKS

1. Define Spanning Tree.

A Spanning Tree is a connected, cycle-free subgraph containing all vertices of a connected, undirected graph.

2 MARKS

2. What Is Minimum Spanning Tree?

An MST is a Spanning Tree having the least total edge weight among all possible Spanning Trees.

2 MARKS

3. How Many Edges Are in a Spanning Tree?

A Spanning Tree of V vertices has exactly V−1 edges.

5 MARKS

4. Explain Prim's Algorithm.

Prim's Algorithm is a greedy algorithm for finding an MST.

It starts from one vertex and repeatedly selects the minimum-weight edge connecting the current tree to a new vertex.

The process stops when all vertices belong to the tree.

5 MARKS

5. Explain Kruskal's Algorithm.

Kruskal's Algorithm first sorts all graph edges by weight.

It selects the cheapest edge that does not create a cycle.

The process continues until V−1 edges have been selected.

10 MARKS

6. Differentiate Spanning Tree and Minimum Spanning Tree with Example.

A Spanning Tree connects all vertices of a connected, undirected graph without forming a cycle.

It contains exactly V−1 edges.

A Minimum Spanning Tree is a Spanning Tree whose total edge weight is minimum among all possible Spanning Trees.

For example, a valid Spanning Tree may contain edges AB(2), AC(3), BD(4) and DE(7).

Its total weight is 16.

However, another Spanning Tree using BC(1), AB(2), BD(4) and CE(6) has total weight 13.

Therefore, the second tree is the MST for our example.

Spanning Tree and MST Practice Questions

Q1. How Many Edges Does a Spanning Tree with 8 Vertices Have?

Show Answer

Edges = V−1 = 8−1 = 7.

Q2. Can a Spanning Tree Contain a Cycle?

Show Answer

No. A Spanning Tree must be cycle-free.

Q3. Which Algorithm Uses DSU?

Show Answer

Kruskal's Algorithm commonly uses DSU to detect whether an edge would create a cycle.

Q4. What Is the MST Cost in Our Example?

Show Solution

Choose BC(1), AB(2), BD(4) and CE(6).

Total = 1+2+4+6 = 13 units.

Q5. Can a Graph Have More Than One MST?

Show Answer

Yes. Some graphs with equal edge weights can have more than one MST with the same minimum total weight.

Q6. Which Is Better for Dense Graphs: Matrix-Based Prim or Heap-Based Prim?

Show Answer

Matrix-based Prim is often suitable for dense graphs because its time complexity is O(V²).

FAQs About Spanning Tree and Minimum Spanning Tree

What is Spanning Tree in simple words?

A Spanning Tree connects all graph vertices without creating a cycle.

What is the main difference between Spanning Tree and MST?

A Spanning Tree only needs connectivity without cycles. An MST also minimizes the total edge weight.

What is the full form of MST?

Minimum Spanning Tree.

Which algorithms find an MST?

Prim's and Kruskal's are two common MST algorithms.

How many edges does an MST have?

An MST with V vertices contains V−1 edges.

Can MST have negative edge weights?

Yes. MST algorithms can work with negative edge weights when implemented correctly. MST minimizes the total edge weight.

Can a disconnected graph have an MST?

A disconnected graph does not have one Spanning Tree covering all vertices. A Minimum Spanning Forest can be found instead.

Is MST the same as shortest path?

No. MST minimizes the total weight of the selected spanning edges. Shortest path algorithms minimize path distance between specified vertices.

Spanning Tree vs MST Quick Revision Notes

SPANNING TREE Includes All Vertices: Yes Cycles: No Edges: V - 1 Minimum Weight Required: No MINIMUM SPANNING TREE Full Form: MST Minimum Total Edge Weight: Yes Edges: V - 1 Cycles: No Common Algorithms: Prim and Kruskal PRIM Grows One Tree Matrix Time: O(V²) Heap-Based Time: O((V+E) log V) KRUSKAL Sort Edges Avoid Cycles Uses DSU Time: O(E log E) OUR EXAMPLE Ordinary Tree Cost: 16 MST Cost: 13

Memory Trick: Spanning Tree = All Vertices + No Cycles. MST = Spanning Tree + Minimum Total Weight.

Conclusion

Spanning Tree and Minimum Spanning Tree are important concepts in Graph Data Structure.

A Spanning Tree connects every vertex without creating cycles.

An MST does the same job while minimizing the sum of selected edge weights.

Prim's Algorithm grows one tree step by step, while Kruskal's Algorithm sorts edges and avoids cycles.

For semester exams, practise drawing a weighted graph, selecting V−1 edges, calculating total weight and performing both algorithms manually.

Chapter 54 — Completed

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources