Skip to content

Commit 15d054f

Browse files
authored
Huffman Coding in C++.
1 parent 3958156 commit 15d054f

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

Huffman_Coding.cpp

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// C++ program for Huffman Coding
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
// A Huffman tree node
5+
struct MinHeapNode
6+
{
7+
// One of the input characters;
8+
char data;
9+
// Frequency of the character;
10+
unsigned freq;
11+
// Left and right child;
12+
MinHeapNode *left, *right;
13+
MinHeapNode(char data, unsigned freq)
14+
{
15+
left = right = NULL;
16+
this->data = data;
17+
this->freq = freq;
18+
}
19+
};
20+
// For comparison of;
21+
// two heap nodes (needed in min heap);
22+
struct compare
23+
{
24+
bool operator()(MinHeapNode* l, MinHeapNode* r)
25+
{
26+
return (l->freq > r->freq);
27+
}
28+
};
29+
// Prints huffman codes from;
30+
// the root of Huffman Tree;
31+
void printCodes(struct MinHeapNode* root, string str)
32+
{
33+
if (!root)
34+
return;
35+
if (root->data != '$')
36+
cout << root->data << ": " << str << endl;
37+
printCodes(root->left, str + "0");
38+
printCodes(root->right, str + "1");
39+
}
40+
// The main function that builds a Huffman Tree and;
41+
// print codes by traversing the built Huffman Tree;
42+
void HuffmanCodes(char data[], int freq[], int size)
43+
{
44+
struct MinHeapNode *left, *right, *top;
45+
// Create a min heap & inserts all characters of data[];
46+
priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap;
47+
for (int i = 0; i < size; ++i)
48+
minHeap.push(new MinHeapNode(data[i], freq[i]));
49+
// Iterate while size of heap doesn't become 1;
50+
while (minHeap.size() != 1)
51+
{
52+
// Extract the two minimum;
53+
// freq items from min heap;
54+
left = minHeap.top();
55+
minHeap.pop();
56+
right = minHeap.top();
57+
minHeap.pop();
58+
// Create a new internal node with
59+
// frequency equal to the sum of the
60+
// two nodes frequencies. Make the
61+
// two extracted node as left and right children
62+
// of this new node. Add this node
63+
// to the min heap '$' is a special value
64+
// for internal nodes, not used;
65+
top = new MinHeapNode('$', left->freq + right->freq);
66+
top->left = left;
67+
top->right = right;
68+
minHeap.push(top);
69+
}
70+
// Print Huffman codes using;
71+
// the Huffman tree built above;
72+
printCodes(minHeap.top(), "");
73+
}
74+
// Driver program to test above functions;
75+
int main()
76+
{
77+
char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
78+
int freq[] = { 5, 9, 12, 13, 16, 45 };
79+
int size = sizeof(arr) / sizeof(arr[0]);
80+
HuffmanCodes(arr, freq, size);
81+
return 0;
82+
}

0 commit comments

Comments
 (0)