forked from Algo-Phantoms/Algo-Tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Huffman_encoding.cpp
121 lines (88 loc) · 2.5 KB
/
Huffman_encoding.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
Given a string S of distinct character of size N and their corresponding frequency f[ ] i.e. character S[i] has f[i] frequency. Our task is to build the Huffman tree print all the huffman codes in preorder traversal of the tree.
Note: If two elements have same frequency, then the element which occur at first will be taken on the left of Binary Tree and other one to the right.
eg.) Input: String --> "abcde"
Frequency_array---> {5,9,12,13,16}
Output: 00 01 100 101 11
*/
#include <bits/stdc++.h>
using namespace std;
// Tree node
struct Node{
char c;
int frequency;
Node *left, *right;
Node(char c, int frequency)
{
this->c = c;
this->frequency = frequency;
left = right = NULL;
}
};
// compare operator that will return the node with larger frequency.
struct compare
{
bool operator() (Node *l, Node *r)
{
return(l->frequency > r->frequency);
}
};
// Function to print the nodes.
void print(Node *root, string str)
{
if(!root)
return;
if(root->c != '%')
cout<<str<<" ";
print(root->left, str + "0");
print(root->right, str + "1");
}
// Huffman Encoding here
void huffmanEncoding(string s, int f[], int n)
{
Node *left, *right, *top;
priority_queue<Node*, vector<Node*>, compare> minh; // Min-heap
// Pushing all the nodes in min-heap. The node with least frequency will be at top.
for(int i = 0; i<n; i++)
{
minh.push(new Node(s[i],f[i]));
}
while(minh.size() != 1)
{
left = minh.top();
minh.pop();
right = minh.top();
minh.pop();
// The new master node made with the sum of two smallest frequencies taken from top on min-heap.
top = new Node('%', left->frequency+right->frequency);
top->left = left;
top->right = right;
minh.push(top);
}
print(minh.top(),"");
}
// main function.
int main() {
string s;
cout<<"Enter the string: ";
cin>>s;
int n = s.size();
int f[n];
cout<<"Enter Frequency: ";
for(int i = 0; i<n; i++)
{
cin>>f[i];
}
huffmanEncoding(s,f,n);
cout<<endl;
return 0;
}
/* Test Cases -
1) S = "abdefgh"
F = {20,2,3,45,1,23,8}
Output = 0 10 11000 110010 110011 1101 111
2) S = "algorithm"
F = {1,2,7,6,5,4,8,7,10}
Output = 00 010 011 100 10100 10101 1011 110 111
*/
// Time Complexity --> O(nlogn)