-
Notifications
You must be signed in to change notification settings - Fork 121
/
Huffman.cpp
165 lines (115 loc) · 2.95 KB
/
Huffman.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Huffman coding algorithm implementation in C++
#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;
#define EMPTY_STRING ""
struct Node
{
char ch;
int freq;
Node *left, *right;
};
Node* getNode(char ch, int freq, Node* left, Node* right)
{
Node* node = new Node();
node->ch = ch;
node->freq = freq;
node->left = left;
node->right = right;
return node;
}
struct comp
{
bool operator()(const Node* l, const Node* r) const
{
return l->freq > r->freq;
}
};
bool isLeaf(Node* root) {
return root->left == nullptr && root->right == nullptr;
}
void encode(Node* root, string str, unordered_map<char, string> &huffmanCode)
{
if (root == nullptr) {
return;
}
// found a leaf node
if (isLeaf(root)) {
huffmanCode[root->ch] = (str != EMPTY_STRING) ? str : "1";
}
encode(root->left, str + "0", huffmanCode);
encode(root->right, str + "1", huffmanCode);
}
void decode(Node* root, int &index, string str)
{
if (root == nullptr) {
return;
}
if (isLeaf(root))
{
cout << root->ch;
return;
}
index++;
if (str[index] == '0') {
decode(root->left, index, str);
}
else {
decode(root->right, index, str);
}
}
void buildHuffmanTree(string text)
{
if (text == EMPTY_STRING) {
return;
}
unordered_map<char, int> freq;
for (char ch: text) {
freq[ch]++;
}
priority_queue<Node*, vector<Node*>, comp> pq;
for (auto pair: freq) {
pq.push(getNode(pair.first, pair.second, nullptr, nullptr));
}
while (pq.size() != 1)
{
Node* left = pq.top(); pq.pop();
Node* right = pq.top(); pq.pop();
int sum = left->freq + right->freq;
pq.push(getNode('\0', sum, left, right));
}
Node* root = pq.top();
unordered_map<char, string> huffmanCode;
encode(root, EMPTY_STRING, huffmanCode);
cout << "Huffman Codes are:\n" << endl;
for (auto pair: huffmanCode) {
cout << pair.first << " " << pair.second << endl;
}
cout << "\nThe original string is:\n" << text << endl;
string str;
for (char ch: text) {
str += huffmanCode[ch];
}
cout << "\nThe encoded string is:\n" << str << endl;
cout << "\nThe decoded string is:\n";
if (isLeaf(root))
{
while (root->freq--) {
cout << root->ch;
}
}
else {
int index = -1;
while (index < (int)str.size() - 1) {
decode(root, index, str);
}
}
}
int main()
{
string text = "Huffman coding is a data compression algorithm.";
buildHuffmanTree(text);
return 0;
}