-
Notifications
You must be signed in to change notification settings - Fork 47
/
Huffman_coding.cpp
66 lines (42 loc) · 947 Bytes
/
Huffman_coding.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
#include <bits/stdc++.h>
using namespace std;
struct Node {
char data;
unsigned freq;
Node *left, *right;
Node(char data, unsigned freq, Node* l = NULL, Node* r = NULL)
{
this->left = l;
this->right = r;
this->data = data;
this->freq = freq;
}
};
struct compare {
bool operator()(Node* l, Node* r)
{
return (l->freq > r->freq);
}
};
void printCodes(struct Node* root, string str)
{
if (!root)
return;
if (root->data != '$')
cout << root->data << ": " << str << "\n";
printCodes(root->left, str + "0");
printCodes(root->right, str + "1");
}
void printHcodes(char arr[], int freq[], int size)
{
priority_queue<Node*, vector<Node*>, compare> h;
for (int i = 0; i < size; ++i)
h.push(new Node(arr[i], freq[i]));
while (h.size() > 1) {
Node *l = h.top();h.pop();
Node *r = h.top();h.pop();
Node *top = new Node('$', l->freq + r->freq, l, r);
h.push(top);
}
printCodes(h.top(), "");
}