-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHuffmanCoding.cpp
More file actions
96 lines (79 loc) · 1.86 KB
/
HuffmanCoding.cpp
File metadata and controls
96 lines (79 loc) · 1.86 KB
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
#include <bits/stdc++.h>
using namespace std;
struct node
{
char ch;
int fr;
node *left, *right;
node(char c, int f)
{
fr = f;
ch = c;
left = right = nullptr;
}
};
struct comp
{
bool operator()(node *a, node *b)
{
return a->fr > b->fr;
}
};
class HuffmanCoding
{
private:
priority_queue<node *, vector<node *>, comp> minHeap; // min-heap priority queue
void printHuffmanCodes(node *root, string s);
public:
void takeInput();
void huffmanTree();
};
void HuffmanCoding::takeInput()
{
int _size;
cout << "Enter number of characters:";
cin >> _size;
char a;
int freq;
while (_size--)
{
cin >> a >> freq;
minHeap.push(new node(a, freq));
}
node *newNode = minHeap.top();
}
void HuffmanCoding::printHuffmanCodes(node *root, string s)
{
if (!root)
{
return;
}
if (root->ch != '$')
{
cout << root->ch << " ->" << s << endl;
}
printHuffmanCodes(root->left, s + "0");
printHuffmanCodes(root->right, s + "1");
}
void HuffmanCoding::huffmanTree()
{
while (minHeap.size() > 1)
{
node *left = minHeap.top(); // taking top most element which is having less frequency
minHeap.pop(); // deleting from the queue
node *right = minHeap.top(); // taking another min freqeuncy holder
minHeap.pop(); // deleted this one too
node *newNode = new node('$', left->fr + right->fr); // storing a new node with freq set to extracted two nodes freq
newNode->left = left; // now new node's left child is first most extracted element
newNode->right = right; // new node's right child is last most extracted element
minHeap.push(newNode); // assigning this sub tree to the min-heap
}
printHuffmanCodes(minHeap.top(), "");
}
int main()
{
HuffmanCoding *demo1 = new HuffmanCoding();
demo1->takeInput();
demo1->huffmanTree();
return 0;
}