DATASTRUCTURE LABmanual
DATASTRUCTURE LABmanual
DATASTRUCTURE LABmanual
1
TREE TRAVERSAL USING RECURSION
DATE :
AIM:
PROCEDURE:
Step1: Start
Step2: To create a node using create node function.
Step3: Read an element (node) using insert node function.
Step4: Using inorder function to arrange elements in the order.
Step4: Print the elements inorder traversal.
Step5: Stop.
SOURCE CODE:
#include<iostream>
using namespace std;
struct node
{
int data;
struct node *left;
struct node
*right;
};
struct node *createnode(int val)
{
struct node *temp=(struct node *)malloc(sizeof(struct node));
temp->data=val;
temp->left=temp-
>right=NULL; return temp;
}
void inorder(struct node *root)
{
if(root!=NULL)
{
inorder(root->left);
cout<<root->data<<"
"; inorder(root->right);
}
}
struct node* insertnode(struct node* node,int val)
{
if(node==NULL)
return
createnode(val);
if(val<node->data)
node->left=insertnode(node->left,val);
else if(val>node->data)
node->right=insertnode(node->right,val);
return node;
}
int main()
{
struct node
*root=NULL;
root=insertnode(root,4);
insertnode(root,5);
insertnode(root,2);
insertnode(root,9);
insertnode(root,1);
insertnode(root,3);
cout<<"inorder traversal of the binary sarch tree is:";
inorder(root);
return 0;
}
OUTPUT
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO: 1.2
FIBONACCI SERIES USING RECURSION
DATE :
AIM:
PROCEDURE:
SOURCE CODE:
#include<iostream>
using namespace
std; int fib(int x)
{
if((x==1||x==0))
{return(x);}
else
{
return(fib(x-1)+fib(x-2));
}}
int main()
{
int x,i=0;
cout<<"enter the number of item of
series:"; cin>>x;
cout<<"\n fibinnaci
series:"; while(i<x)
{cout<<" "<<fib(i); i++;}
return 0;
}
OUTPUT
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO: 2 ITERATION FUNCTION FOR FIBONACCI
DATE :
AIM
To implementation of iteration function for Fibonacci Series.
PROCEDURE:
STEP5: If the condition is true, then it will execute the code inside the block of For loop. If the
condition is false, it will jump to the code after the For loop without executing the for loop code.
STEP6: After the For loop, the increment statement will be executed. After that again, the condition
will be checked. Loop will get executed if the condition is true, and the loop will repeat itself, i.e. the
body of the loop, an increment statement, and condition. The For loop ends when the condition is
false
#include<iostream>
using namespace
std; void fib(int
num)
{
int x=0,y=1,z=0;
for(int
i=0;i<num;i++)
{
cout<<x<<"
,"; z=x+y;
x=y
;
y=z
;
}
}
int main()
{
int num;
cout<<"Enter the
number:"; cin>>num;
cout<<"\n The fibonacci
series:"; fib(num);
return 0;
}
OUTPUT
RESULT:
Thus the above program was executedsuccessfullyy and output also verified.
EX NO: 3.1
MERGE SORT
DATE :
AIM:
PROCEDURE:
#include<iostream>
using namespace
std;
void swapping(int &a,int &b)
{
int
temp;
temp=a;
a=b;
b=temp;
}
void display(int *array,int size)
{
for(int
i=0;i<size;i++)
cout<<array[i]<<" ";
cout<<endl;
}
void merge(int *array,int l,int m,int r)
{
int
i,j,k,nl,nr;
nl=m-l+1;
nr=r-m;
int larr[nl],rarr[nr];
//fill left and right sun-
arays for(i=0;i<nl;i++)
larr[i]=array[l+i];
for(j=0;j<nr;j++)
rarr[j]=array[m+1+j];
i=0
;
j=0
;
k=l;
//merge temp arrays to real
array while(i<nl&&j<nr)
{
if(larr[i]<=rarr[j])
{
array[k]=larr[i
]; i++;
}
else
{
array[k]=rarr[j]
; j++;
}k++;
}
while(i<nl)//extra element in left array
{
array[k]=larr[i
]; i++;
k++;
}
while(j<nr)
{
array[k]=rarr[j]
; j++;
k++;
}
OUTPUT
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO: 3.2 QUICK SORT
DATE :
AIM:
PROCEDURE:
Step 1 - Consider the first element of the list as pivot (i.e., Element at first position in the
list).
Step 2 - Define two variables i and j. Set i and j to first and last elements of the list
respectively.
Step 3 - Increment i until list[i] > pivot then stop.
Step 4 - Decrement j until list[j] < pivot then stop.
Step 5 - If i < j then exchange list[i] and list[j].
Step 6 - Repeat steps 3,4 & 5 until i > j.
Step 7 - Exchange the pivot element with list[j] element.
SOURCE CODE:
#include<cstdlib>
using namespace
std;
void swap(int *a, int *b)
{
int temp;
temp =
*a;
*a = *b;
*b = temp;
}
Int Partition(int a[], int l, int h)
{
int pivot, index,
i; index = l;
pivot = h;
for(i = l; i < h; i++)
{
if(a[i] < a[pivot])
{
swap(&a[i],
&a[index]); index++;
}
}
swap(&a[pivot],
&a[index]); return index;
}
int RandomPivotPartition(int a[], int l, int h)
{
int pvt, n,
temp; n =
rand();
pvt = l + n%(h-l+1);
swap(&a[h], &a[pvt]);
return Partition(a, l, h);
}
int QuickSort(int a[], int l, int h)
{
int
pindex;
if(l < h) {
pindex = RandomPivotPartition(a, l,
h); QuickSort(a, l, pindex-1);
QuickSort(a, pindex+1, h);
}return 0;
}
int main()
{ int n, i;
cout<<"\nEnter the number of data element to be sorted:
"; cin>>n;
int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<":
"; cin>>arr[i];
}
QuickSort(arr, 0, n-1);
cout<<"\nSorted Data
"; for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
}
OUTPUT
Enter element 3: 88
Enter element 4: 22
Enter element 5: 33
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO: 4
BINARY SEARCH TREE
DATE :
AIM:
PROCEDURE:
#include<iostream> using
namespace std;
int binarySearch(int arr[], int p, int r, int num) { if (p <=
r) {
int mid = (p + r)/2; if (arr[mid] ==
num)
return mid ;
if (arr[mid] > num)
return binarySearch(arr, p, mid-1, num); if (arr[mid] <
num)
return binarySearch(arr, mid+1, r, num);
}
return -1;
}
int main(void) {
int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
int n = sizeof(arr)/ sizeof(arr[0]); int num;
cout << "Enter the number to search: \n"; cin >>
num;
int index = binarySearch (arr, 0, n-1, num); if(index ==
-1){
cout<< num <<" is not present in the array";
}else{
cout<< num <<" is present at index "<< index <<" in the array";
}
return 0;
}
OUTPUT
mca37@localhost mca37]$ gcc bs.cpp -lstdc++
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO: 5
RED-BLACK TREE
DATE :
AIM:
PROCEDURE:
Deletion:
First, search for an element to be deleted
o If the element to be deleted is in a node with only left child, swap this node with one containing the largest
element in the left subtree. (This node has no right child).
o If the element to be deleted is in a node with only right child, swap this node with the one containing the
smallest element in the right subtree (This node has no left child).
o If the element to be deleted is in a node with both a left child and a right child, then swap in any of the
above two ways. While swapping, swap only the keys but not the colors.
o The item to be deleted is now having only a left child or only a right child. Replace this node with its sole
child. This may violate red constraints or black constraint. Violation of red constraints can be easily fixed.
o If the deleted node is black, the black constraint is violated. The elimination of a black node y causes any
path that contained y to have one fewer black node.
o Two cases arise:
o The replacing node is red, in which case we merely color it black to make up for the loss of one black node.
o The replacing node is black.
SOURCE CODE:
#include
<bits/stdc++> using
namespace std;
enum Color {RED,
BLACK}; struct Node
{
int data; bool
color;
Node *left, *right, *parent;
// Constructor
Node(int data)
{
this->data = data;
left = right = parent = NULL; this-
>color = RED;
}
};
// Class to represent Red-Black
Tree class RBTree
{
private:
Node *root;
protected:
void rotateLeft(Node *&, Node *&); void
rotateRight (Node *&, Node *&); void
fixViolation (Node *&, Node *&);
// Constructor
public RBTree() { root = NULL; } void insert(const int &n);
void inorder();
void levelOrder();
// A recursive function to do inorder
traversal void inorderHelper(Node *root)
{
if (root == NULL)
return;
inorderHelper(root->left); cout
<< root->data << " ";
inorderHelper(root->right);
}
/* A utility function to insert a new node with given key in BST */
Node* BSTInsert(Node* root, Node *pt)
{
/* If the tree is empty, return a new node */ if
(root == NULL)
return pt;
pt->right->parent = pt;
pt_right->parent = pt->parent; if (pt-
>parent == NULL)
root = pt_right;
else if (pt == pt->parent->left)
pt->parent->left = pt_right;
else
pt->parent->right = pt_right;
pt_right->left = pt;
pt->parent = pt_right;
}
void RBTree::rotateRight(Node *&root, Node *&pt)
{
Node *pt_left = pt->left; pt-
>left = pt_left->right;
if (pt->left != NULL)
pt->left->parent = pt;
pt_left->parent = pt->parent;
if (pt->parent == NULL)
root = pt_left;
/* Case : 1
The uncle of pt is also red Only
Recoloring required */
rotateRig
ht(root,
parent_pt
); pt =
parent_pt;
parent_pt = pt->parent;
}
/* Case : 3
pt is right child of its parent Left-rotation required */
rotateLeft(root, grand_parent_pt); swap(parent_pt->color,
grand_parent_pt->color);
pt = parent_pt;
}
}
}
root->color = BLACK;
}
// Function to insert a new node with given
data void RBTree::insert(const int &data)
{
Node *pt = new Node(data);
// Do a normal BST insert root =
BSTInsert(root, pt);
// fix Red Black Tree violations
fixViolation(root, pt);
}
// Function to do inorder and level order traversals
void RBTree::inorder() { inorderHelper(root);}
void RBTree::levelOrder() { levelOrderHelper(root);
}
// Driver
Code int
main()
{
RBTree tree;
tree.insert(7);
tree.insert(6);
tree.insert(5);
tree.insert(4);
tree.insert(3);
tree.insert(2);
tree.insert(1);
cout << "Inorder Traversal of Created Tree\n";
tree.inorder();
cout << "\n\nLevel Order Traversal of Created Tree\n";
tree.levelOrder();
return 0;
}
OUTPUT
RESULT
Thus the program is executed successfully and the output also verified.
EX NO: 6
HEAP IMPLEMENTATION
DATE :
AIM:
PROCEDURE:
3. Start from the first index of non-leaf node whose index is given by n/2 - 1.Start from the firston leaf node.
5. The index of the left child 2i+1 and right child 2i+2. If left child is greater than current element (i.e. element in
ith index), set leftchild is largest.
#include
<iostream> using
namespace std;
void min_heap(int *a, int m, int n){
int j, t;
t= a[m];
j = 2 * m; while
(j <= n) {
if (j < n && a[j+1] < a[j]) j = j
+ 1;
if (t < a[j])
break;
else if (t >= a[j]) {
a[j/2] = a[j]; j =
2 * j;
}
}
a[j/2] = t;
return;
}
void build_minheap(int *a, int n) {
int k;
for(k = n/2; k >= 1; k--) {
min_heap(a,k,n);
}
}
int main() {
int n, i;
cout<<"enter no of elements of array\n";
cin>>n;
int a[30];
for (i = 1; i <= n; i++) {
cout<<"enter element"<<" "<<(i)<<endl;
cin>>a[i];
}
build_minheap(a, n);
cout<<"Min Heap\n";
for (i = 1; i <= n; i++) {
cout<<a[i]<<endl;
}
return 0;}
OUTPUT
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO: 7
DATE : FIBONACCI HEAP IMPLEMENTATION
AIM:
PROCEDURE:
Insertion
It is the most important operation on a fibonacci heap. In this operation, the node with minimum value is
removed from the heap and the tree is re-adjusted.
The following steps are followed:
1. Delete the min node.
3. Create an array of size equal to the maximum degree of the trees in the heap before deletion.
4. Do the following (steps 5-7) until there are no multiple roots with the same degree.
5. Map the degree of current root (min-pointer) to the degree in the array.
7. If there are more than two mappings for the same degree, then apply union operation to those roots such
that the min-heap property is maintained (i.e. the minimum is at the root).
SOURCE CODE:
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO: 8.1
DATE : GRAPH TRAVESALS-BFS
AIM:
PROCEDURE:
Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front of the Queue and insert them
into the Queue.
Step 4 - When there is no new vertex to be visited from the vertex which is at front of the Queue then delete
that vertex.
Step 5 - Repeat steps 3 and 4 until queue becomes empty.
Step 6 - When queue becomes empty, then produce final spanning tree by removing unused edges from the
graph
SOURCE CODE:
#include<iostream>
#include<list>
using namespace
std; class Graph {
int numVertices;
list<int>*
adjLists; bool*
visited; public:
Graph(int vertices);
void addEdge(int src, int
dest); void BFS(int
startVertex);
}; //
Create a graph with given vertices,
// and maintain an adjacency
list Graph::Graph(int vertices)
{ numVertices = vertices;
adjLists = new list<int>[vertices];
} //
Add edges to the graph
void Graph::addEdge(int src, int dest)
{ adjLists[src].push_back(dest);
adjLists[dest].push_back(src);
} //
BFS algorithm
void Graph::BFS(int startVertex)
{ visited = new
bool[numVertices]; for (int i = 0; i
< numVertices; i++) visited[i] =
false;
list<int> queue;
visited[startVertex] = true;
queue.push_back(startVertex);
list<int>::iterator i;
while (!queue.empty()) {
int currVertex = queue.front();
cout << "Visited " << currVertex << "
"; queue.pop_front();
for (i = adjLists[currVertex].begin(); i != adjLists[currVertex].end(); ++i)
{
int adjVertex = *i;
if (!visited[adjVertex]) {
visited[adjVertex] = true;
queue.push_back(adjVertex);
}
}
}
}
int main()
{
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.BFS(2);
return 0;
}
OUTPUT
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO: 8.2
GRAPH TRAVESALS-DFS
DATE :
AIM:
To create a graph traversal(DFS) using C++.
PROCEDURE:
DFS traversal
#include
<iostream>
#include<vector>
using namespace
std;
int main()
{
cout << " ===== Program to demonstrate the DFS Traversal on a Graph, in CPP ===== \n\n";
//variable declaration
int cost[10][10], i, j, k, n, e, top, v, stk[10], visit[10], visited[10];
cout << "Enter the number of vertices in the Graph: ";
cin >> n;
cout << "\nEnter the number of edges in the Graph : ";
cin >> e;
cout << "\nEnter the start and end vertex of the edges: \n";
for (k = 1; k <= e; k++)
{
cin >> i >> j;
cost[i][j] = 1;
}
cout << "\nEnter the initial vertex to start the DFS traversal with: ";
cin >> v;
cout << "\nThe DFS traversal on the given graph is : \n";
cout << v << " ";
//As we start with the vertex v, marking it visited to avoid visiting again
visited[v] = 1;
k = 1;
//The DFS Traversal Logic
while (k < n)
{
for (j = n; j >= 1; j--)
{
if (cost[v][j] != 0 && visited[j] != 1 && visit[j] != 1)
{
visit[j] = 1;
//put all the vertices that are connected to the visited vertex into a stack stk[top]
= j;
top++;
}
}
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO:9
SPANNING TREE IMPLEMENTATION
DATE :
AIM:
PROCEDURE:
#include<iostream>
using namespace
std;
// Number of vertices in the
graph const int V=6;
// Function to find the vertex with minimum key
value int min_Key(int key[], bool visited[])
{
int min = 999, min_index; // 999 represents an Infinite value
Edge Weight
5-1 3
5-2 1
2-3 3
3-4 2
0-5 2
Total cost is 11
RESULT:
Thus the program is executed successfully and the output also verified.
.
EX NO:10.1
DATE : SHORTEST PATH ALGORITHMS -DIJKSTRA ALGORITHM
AIM:
PROCEDURE
2. Maintain a list of unvisited vertices. Assign a vertex as “source” and also allocate a maximum
possible cost (infinity) to every other vertex. The cost of the source to itselfwill be zero as it
actually takes nothing to go to itself.
3. In every step of the algorithm, it tries to minimize the cost for each vertex.
4. For every unvisited neighbor (V2, V3) of the current vertex (V1) calculate the new cost from V1.
5. The new cost of V2 is calculated as :
Minimum( existing cost of V2 , (sum of cost of V1 + the cost of edge from V1 to V2) )
7. When all the neighbors of the current node are visited and cost has been calculated,
mark the current node V1 as visited and remove it from the unvisited list.
8. Select next vertex with smallest cost from the unvisited list and repeat from step 4.
9. The algorithm finally ends when there are no unvisited nodes left.
SOURCE CODE:
#include<iostream>
#include<climits> using
namespace std;
int miniDist(int distance[], bool Tset[]) // finding minimum distance
{
int minimum=INT_MAX,ind;
for(int k=0;k<6;k++)
{
if(Tset[k]==false && distance[k]<=minimum)
{
minimum=distance[k]; ind=k;
}
}
return ind;
}
void DijkstraAlgo(int graph[6][6],int src) // adjacency matrix
{
int distance[6]; // // array to calculate the minimum distance for each node bool
Tset[6];// boolean array to mark visited and unvisited for each node
for(int k = 0; k<6; k++)
{
distance[k] = INT_MAX; Tset[k] =
false;
}
distance[src] = 0; // Source vertex distance is set 0
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO:10.2 SHORTEST PATH ALGORITHM BELLMAN
DATE : FORD ALGORITHM
AIM:
PROCEDURE:
1) Initializing the source vertex with distance to itself as 0 and all other vertices as
infinity.Creating the array with size N
2) Calculate the shortest distance from the source vertex. Following this process for N-
1times where N is the number of vertices in the graph
3) For relaxing the path lengths for the vertices for each edge m-n:
#include<iostream>
#define MAX 10
using namespace
std;
typedef struct edge
{
int src;
int dest;
int wt;
}edge;
void bellman_ford(int nv,edge e[],int src_graph,int ne)
{
int u,v,weight,i,j=0;
int dis[MAX];
/* initializing array 'dis' with 999. 999 denotes infinite distance */
for(i=0;i<nv;i++)
{
dis[i]=999;
}
/* distance of source vertex from source vertex is o */
dis[src_graph]=0;
/* relaxing all the edges nv - 1 times */
for(i=0;i<nv-1;i++)
{
for(j=0;j<ne;j++)
{
u=e[j].src;
v=e[j].dest;
weight=e[j].wt;
if(dis[u]!=999 && dis[u]+weight < dis[v])
{
dis[v]=dis[u]+weight;
}
}}
/* checking if negative cycle is present */
for(j=0;j<ne;j++)
{
u=e[j].src;
v=e[j].dest;
weight=e[j].wt;
if(dis[u]+weight < dis[v])
{
cout<<"\n\nNEGATIVE CYCLE PRESENT..!!\n";
return;
}
}
cout<<"\nVertex"<<" Distance from source";
for(i=1;i<=nv;i++)
{
cout<<"\n"<<i<<"\t"<<dis[i];
}
}
int main()
{
int nv,ne,src_graph;
edge e[MAX];
cout<<"Enter the number of vertices: ";
cin>>nv;
/* if you enter no of vertices: 5 then vertices will be 1,2,3,4,5. so while gi
ving input enter source and destination vertex accordingly */ 20,1 46%
printf("Enter the source vertex of the graph: ");
cin>>src_graph;
cout<<"\nEnter no. of edges: ";
cin>>ne;
for(int i=0;i<ne;i++)
{
cout<<"\nFor edge "<<i+1<<"=>";
cout<<"\nEnter source vertex :";
cin>>e[i].src;
cout<<"Enter destination vertex :";
cin>>e[i].dest;
cout<<"Enter weight :";
cin>>e[i].wt;
}
bellman_ford(nv,e,src_graph,ne);
return 0;
}
OUTPUT
[mca37@localhost mca37]$
./a.out Enter the number of
vertices: 4
Enter the source vertex of the graph:
1 Enter no. of edges: 4
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO:11 MATRIX CHAIN MULTIPLICATION
DATE :
AIM:
ALGORITHM:
MATRIX-CHAIN-ORDER (p)
1. n length[p]-1
2. for i ← 1 to n
3. do m [i, i] ← 0
5. do for i ← 1 to n-l + 1
6. do j ← i+ l -1
7. m[i,j] ← ∞
8. for k ← i to j-1
9. do q ← m [i, k] + m [k + 1, j] + pi-1 pk pj
10. If q < m [i,j]
12. s [i,j] ← k
#include<iostream>
using namespace
std;
int matOrder(int array[], int n){
int minMul[n][n]; //holds the number of scalar multiplication needed
for (int i=1; i<n; i++)
minMul[i][i] = 0; //for multiplication with 1 matrix, cost is 0
for (int length=2; length<n; length++){ //find the chain length starting from 2 for
(int i=1; i<n-length+1; i++){
int j = i+length-1;
minMul[i][j] = INT_MAX; //set to infinity for
(int k=i; k<=j-1; k++){
//store cost per multiplications
int q = minMul[i][k] + minMul[k+1][j] + array[i-1]*array[k]*array[j]; if (q <
minMul[i][j])
minMul[i][j] = q;
}
}
}
return minMul[1][n-1];
}
int main(){
int arr[] = {1, 2, 3, 4};
int size = 4;
cout << "Minimum number of matrix multiplications: "<<matOrder(arr, size);
}
OUTPUT
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO:12.1
ACTIVITY SELECTION IMPLEMENTATION
DATE :
AIM:
PROCEDURE
Begin
initially sort the given activity List set i := 1
display the i-th activity //in this case it is the first activity for j := 1 to n-1 do
if start time of act[j] >= end of act[i] then display the jth activity
i := j
done End
SOURCE CODE:
#include<iostream>
#include<algorithm
> using namespace
std; struct Activitiy{
int start, end;
};
bool comp(Activitiy act1, Activitiy act2){
return (act1.end < act2.end);
}
void maxActivity(Activitiy act[], int n){
//sort activities using compare function
sort(act, act+n, comp);
cout << "Selected Activities are: " << endl;
int i = 0;// first activity as 0 is selected
cout << "Activity: " << i << " , Start: " <<act[i].start << " End: " << act[i].end <<endl;
for (int j = 1; j < n; j++){ //for all other activities
if (act[j].start >= act[i].end){ //when start time is >= end time, print the activity
cout << "Activity: " << j << " , Start: " <<act[j].start << " End: " << act[j].end <<endl; i = j;
}
}
}
int main()
{
Activitiy actArr[] = {{5,9},{1,2},{3,4},{0,6},{5,7},{8,9}};
int n = 6;
maxActivity(actArr,n);
return 0;
}
OUTPUT
RESULT:
Thus the program is executed successfully and the output also verified.
EX NO:12.2 HUFFMAN CODING IMPLEMENTATION
DATE :
AIM:
PROCEDURE
2. Sort the characters in increasing order of the frequency. These are stored in a priorityqueue
Q.Characters sorted according to the frequency
4. Create an empty node Z. Assign the minimum frequency of the left child of Z and second the
minimum frequency of the right child of Z .set the value of z as sum of the above two frequencies.
5. Remove these two minimum frequencies from Q and add the sum into the list of frequencies.
7. Repeat steps 3 to 5 for all the characters. Repeat steps 3 to 5 for all the characters. Repeatsteps 3 to 5
for all the characters.
8. For each non-leaf node, assign 0 to the left edge and 1 to the right edge
calculate the sum of these two minimum values and assign it to the value of newNodeinsert this
newNode into the tree
return rootNode
SOURCE CODE:
#include
<iostream>
#include <vector>
#include <queue>
#include <string>
using namespace std;
class
Huffman_Codes
{
struct New_Node
{
char data;
size_t freq;
New_Node* left;
New_Node* right;
New_Node(char data, size_t freq) : data(data),
freq(freq),
left(NULL),
right(NULL
)
{}
~New_Node()
{
delete left;
delete right;
}
};
struct compare
{
bool operator()(New_Node* l, New_Node* r)
{
return (l->freq > r->freq);
}
};
New_Node* top;
}
}
public:
Huffman_Codes() {};
~Huffman_Codes()
{
delete top;
}
void Generate_Huffman_tree(vector<char>& data, vector<size_t>& freq, size_t size)
{
New_Node* left;
New_Node* right;
priority_queue<New_Node*, vector<New_Node*>, compare > minHeap;
for(size_t i = 0; i < size; ++i)
{
minHeap.push(new New_Node(data[i], freq[i]));
}
while(minHeap.size() != 1)
{
left =
minHeap.top();
minHeap.pop();
right =
minHeap.top();
minHeap.pop();
}
cout<<"Enter the frequencies \n";
for (int i=0;i<n;i++)
{
cin>>f;
freq.insert(freq.end(),
f);
}
Enter the
characters a e i o u
st
RESULT:
Thus the program is executed successfully and the output also verified.