Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced B Tree in Data Structure Convert Sorted List to Binary Search Tree Flattening a Linked List Given a Perfect Binary Tree, Reverse Alternate Levels Left View of Binary Tree What are Forest Trees in Data Structure Compare Balanced Binary Tree and Complete Binary Tree Diameter of a Binary Tree Given a Binary Tree Check the Zig Zag Traversal Given a Binary Tree Print the Shortest Path Given a Binary Tree Return All Root To Leaf Paths Given a Binary Tree Swap Nodes at K Height Given a Binary Tree Find Its Minimum Depth Given a Binary Tree Print the Pre Order Traversal in Recursive Given a Generate all Structurally Unique Binary Search Trees Perfect Binary Tree Threaded Binary Trees Function to Create a Copy of Binary Search Tree Function to Delete a Leaf Node from a Binary Tree Function to Insert a Node in a Binary Search Tree Given Two Binary Trees, Check if it is Symmetric A Full Binary Tree with n Nodes Applications of Different Linked Lists in Data Structure B+ Tree in Data Structure Construction of B tree in Data Structure Difference between B-tree and Binary Tree Finding Rank in a Binary Search Tree Finding the Maximum Element in a Binary Tree Finding the Minimum and Maximum Value of a Binary Tree Finding the Sum of All Paths in a Binary Tree Time Complexity of Selection Sort in Data Structure How to get Better in Data Structures and Algorithms Binary Tree Leaf Nodes Classification of Data Structure Difference between Static and Dynamic Data Structure Find the Union and Intersection of the Binary Search Tree Find the Vertical Next in a Binary Tree Finding a Deadlock in a Binary Search Tree Finding all Node of k Distance in a Binary Tree Finding Diagonal Sum in a Binary Tree Finding Diagonal Traversal of The Binary Tree Finding In-Order Successor Binary Tree Finding the gcd of Each Sibling of the Binary Tree Greedy Algorithm in Data Structure How to Calculate Space Complexity in Data Structure How to find missing numbers in an Array Kth Ancestor Node of Binary Tree Minimum Depth Binary Tree Mirror Binary Tree in Data Structure Red-Black Tree Insertion Binary Tree to Mirror Image in Data Structure Calculating the Height of a Binary Search Tree in Data Structure Characteristics of Binary Tree in Data Structure Create a Complete Binary Tree from its Linked List Field in Tree Data Structure Find a Specified Element in a binary Search Tree Find Descendant in Tree Data Structure Find Siblings in a Binary Tree Given as an Array Find the Height of a Node in a Binary Tree Find the Second-Largest Element in a Binary Tree Find the Successor Predecessor of a Binary Search Tree Forest of a Tree in Data Structure In Order Traversal of Threaded Binary Tree Introduction to Huffman Coding Limitations of a Binary Search Tree Link State Routing Algorithm in Data Structure Map Reduce Algorithm for Binary Search Tree in Data Structure Non-Binary Tree in Data Structure Quadratic Probing Example in Hashing Scope and Lifetime of Variables in Data Structure Separate Chaining in Data Structure What is Dynamic Data Structure Separate Chaining vs Open Addressing Time and Space Complexity of Linear Data Structures Abstract Data Types in Data Structures Binary Tree to Single Linked List Count the Number of Nodes in the Binary Tree Count Total No. of Ancestors in a Binary Search Tree Elements of Dynamic Programming in Data Structures Find cost of tree with prims algorithm in data structures Find Preorder Successor in a Threaded Binary Tree Find Prime Nodes Sum Count in Non-Binary Tree Find the Right Sibling of a Binary Tree with Parent Pointers Find the Width of the Binary Search Tree Forest trees in Data Structures Free Tree in Data Structures Frequently asked questions in Tree Data Structures Infix, Postfix and Prefix Conversion Time Complexity of Fibonacci Series What is Weighted Graph in Data Structure What is the Advantage of Linear Search?

Minimum Spanning Tree

Before getting to know about the minimum spanning tree, we should first discuss about what is a spanning tree. A spanning tree is basically a sub or minimized graph that comes from an undirected graph. This means that a specific minimum spanning tree generally contains all the numbers of edges present in the graph and that too with almost the least type of edges. In case there appears to be a case where the vertex is skipped, then it is not considered as a spanning tree. The edges present in the spanning tree don’t contain the mass that is specified to them. Suppose we have a graph that contains the total ‘n’ number of edges, then the total amount of spanning trees that can be created is given by the expression; nn-2.

What is a minimum spanning tree?

The minimum spanning tree is often described as the one where the sum of the edges is the least or minimum. It is called a minimum spanning tree because in this, the cost is very little, or you can say the least when you compare it with the rest of the spanning trees. It is the kind of tree that has a great impact on the designing field and also in the networking areas. It is a tree that doesn’t contain any cycles within it and with the least possible weight. It is the one tree in which the combined weight or mass of all the edges turns out to be as small as possible.

Properties of the minimum spanning tree

There are mainly seven properties in a minimum spanning tree. We will discuss them one by one in detail below: -

  1. Multiplicity
    Suppose if we have n number of edges present, then the minimum spanning tree is told to be n-1 edges.
  2. Cut property
    The cut property in an MST generally signifies that if we cut a graph of any sort, then the edge we just trimmed with the least weight will always be part of the minimum spanning tree.
  3. Cycle property
    The cycle property in an MST generally signifies that the edge which contains or occupies the maximum amount of weight will never be considered as a part of the minimum spanning tree.
  4. Contraction
    Let us suppose we have a tree which is called T and being a tree. It already has some edges within itself; then, we can simply converge this T into one single vertex while maintaining the relationship between the contracted graph and the graph before the contraction.
  5. Uniqueness
    If somehow, there is an edge that contains a distinct weight, then it will have one and only one minimum spanning tree. There are many applications rationalized based on the same principle; some of them are forests, telecommunication companies, and several others.
  6. Least cost subgraph
    If the measures we have, are somehow positive, then the minimum spanning tree actually turns into a minimum cost subgraph that helps us in linking all the edges and vertices.
  7. Least cost edge
    If we know that the minimum cost edge of a tree is somewhat unique, then the edges present in there are typically in any kind of MST, which is a minimum spanning tree.

Types of algorithms used

There are two major kinds of the algorithm used for finding out the minimum spanning tree. They are: -

  • Kruskal's algorithm
  • Prim’s algorithm

Let us discuss them one by one.

Kruskal's algorithm

Kruskal’s algorithm is known for its application in finding the minimal spanning forest. In this algorithm, if the graph is combined, then it relocates the minimum spanning tree. It is known as a greedy algorithm in the history of graphs, as when we move ahead, we search for the next least weighted edge, which will not be able to form a wheel or cycle in the graph. It was discovered by Joseph Kruskal in the year 1956.

It is an algorithm that is particularly used for searching the minimum spanning tree for a graph that is interconnected and weighted in nature. The primary focus of the algorithm is to search and relocate the sub-group of edges by the usage of crossing each and every vertex of the whole graph. It escorts the approach that searches for an optimum resolution at each and every corner or stage rather than concentrating on a single global optimum.

Implementation of Kruskal's algorithm in C++

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;


#define edge pair<int, int>


class Graph {
   private:
  vector<pair<int, edge> > G;  // graph
  vector<pair<int, edge> > T;  // mst
  int *parent;
  int V;  // number of vertices/nodes in graph
   public:
  Graph(int V);
  void AddWeightedEdge(int u, int v, int w);
  int find_set(int i);
  void union_set(int u, int v);
  void kruskal();
  void print();
};
Graph::Graph(int V) {
  parent = new int[V];


  //i 0 1 2 3 4 5
  //parent[i] 0 1 2 3 4 5
  for (int i = 0; i < V; i++)
    parent[i] = i;


  G.clear();
  T.clear();
}
void Graph::AddWeightedEdge(int u, int v, int w) {
  G.push_back(make_pair(w, edge(u, v)));
}
int Graph::find_set(int i) {
  // If i is the parent of itself
  if (i == parent[i])
    return i;
  else
    // Else if i is not the parent of itself
    // Then, i is not the representative of his set,
    // so we recursively call Find on its parent
    return find_set(parent[i]);
}


void Graph::union_set(int u, int v) {
  parent[u] = parent[v];
}
void Graph::kruskal() {
  int i, uRep, vRep;
  sort(G.begin(), G.end());  // increasing weight
  for (i = 0; i < G.size(); i++) {
    uRep = find_set(G[i].second.first);
    vRep = find_set(G[i].second.second);
    if (uRep != vRep) {
      T.push_back(G[i]);  // add to tree
      union_set(uRep, vRep);
    }
  }
}
void Graph::print() {
  cout << "Edge :"
     << " Weight" << endl;
  for (int i = 0; i < T.size(); i++) {
    cout << T[i].second.first << " - " << T[i].second.second << " : "
       << T[i].first;
    cout << endl;
  }
}
int main() {
  Graph g(6);
  g.AddWeightedEdge(0, 1, 4);
  g.AddWeightedEdge(0, 2, 4);
  g.AddWeightedEdge(1, 2, 2);
  g.AddWeightedEdge(1, 0, 4);
  g.AddWeightedEdge(2, 0, 4);
  g.AddWeightedEdge(2, 1, 2);
  g.AddWeightedEdge(2, 3, 3);
  g.AddWeightedEdge(2, 5, 2);
  g.AddWeightedEdge(2, 4, 4);
  g.AddWeightedEdge(3, 2, 3);
  g.AddWeightedEdge(3, 4, 3);
  g.AddWeightedEdge(4, 2, 4);
  g.AddWeightedEdge(4, 3, 3);
  g.AddWeightedEdge(5, 2, 2);
  g.AddWeightedEdge(5, 4, 3);
  g.kruskal();
  g.print();
  return 0;
}

Output:

Minimum Spanning tree

Prim’s Algorithm

Prim’s algorithm is used to find out the minimum spanning tree with a weighted undirected graph. What it means is that it purposely searches a sub-group of all the vertices or the edges of the tree, and after that, the total mass of the edges is reduced. This type of algorithm initially functions on the principle of constructing one vertex at a given point of time. From adding on and starting with any random vertex and then carrying out and connecting the cheapest possible connection from the tree to another vertex. Prim’s algorithm is known to be the one that begins with a specific vertex and then resumes in adding the edges with the tinniest weight unless and until the goal is reached.

Implementation of prim’s algorithm

#include <cstring>
#include <iostream>
using namespace std;
// the total amount of vertices in the graph is: -
#defining V 5


// Below, we will be creating a 2d array that has a size of 5*5
//We will now describe the adjacency matrix to simply present a graph 


int G[X][X] = {
  {0, 9, 75, 0, 0},
  {9, 0, 95, 19, 42},
  {75, 95, 0, 51, 66},
  {0, 19, 51, 0, 31},
  {0, 42, 66, 31, 0}};


int main() {
  int n_edge;  // total number of edges


  // Now, we will create an array that will help us track all the chosen vertices 
  // the ones that are chosen will become true, and others will become false 
  int select[V];


  // set the chosen false initially 
  memset(select, false, sizeof(selected));


  // Now, we have to initialize and set the number of edges to 0
  n_edge = 0;


  // Depicting the number of edges in an MST: - 
  // It will always be less than (X-1), where we know that X is the number of vertices present 
  //graph is depicted below


  // we will now select the 0th vertex and make it true 
  select[0] = true;


  int a;  //  row number
  int b;  //  col number


  // present by printing the edge and weight
  cout << "Edge"
     << " : "
     << "Weight";
  cout << endl;
  while (no_edge < X - 1) {
    //For every single vertex in the set M, find all adjacent vertices
    //count the distance from the vertex that was chosen in step 1.
    // if by any chance the vertex is already present in set M then it’s fine. In any other case, dismiss it. 
    //Select any other vertex which is closest to the chosen vertex in step 1. 


    int min = INF;
    a = 0;
    b = 0;


    for (int i = 0; i < X; i++) {
      if (selected[i]) {
        for (int j = 0; j < X; j++) {
          if (!selected[j] && H[i][j]) {  // not in selected and there is an edge
            if (min > H[i][j]) {
              min = H[i][j];
              a = i;
              b = j;
            }
          }
        }
      }
    }
    cout << a << " - " << b << " :  " << H[a][b];
    cout << endl;
    selected[b] = true;
    n_edge++;
  }


  return 0;
}

Output:

Minimum Spanning tree