Question: / / C + + Program for Huffman Coding using Priority Queue #include #include using namespace std; #define MAX _ SIZE 1 0 0 /
C Program for Huffman Coding using Priority Queue
#include
#include
using namespace std;
#define MAXSIZE Maximum Height of Huffman Tree.
class HuffmanTreeNode
public:
char data; Stores character
int freq; Stores frequency of the character
HuffmanTreeNode left; Left child of the current node
HuffmanTreeNode right; Right child of the current node
HuffmanTreeNodechar character, int frequency Initializing the current node
data character;
freq frequency;
left right NULL;
;
Custom comparator class
class Compare
public:
bool operatorHuffmanTreeNode a HuffmanTreeNode b
Defining priority on the basis of frequency
return afreq bfreq;
;
Function to generate Huffman Encoding Tree
HuffmanTreeNode generateTreepriorityqueue, Compare pq
We keep on looping till only one node remains in the Priority Queue
while pqsize
Remove nodes ni nj with lowest frequencies pi pj from the Priority Queue
Create a new symbol could be a anything, it won't be used
with the new frequency pipj we are only concerned with the frequency
A new node is formed with the new symbol and frequency
set the left and right children of the newely formed node to be ni and nj
Push back node created to the Priority Queue
The Priority Queue should have one element: the entire Tree
return pqtop;
Function to print the huffman code for each character.
It uses arr to store the codes
void printCodesHuffmanTreeNode root, int arr int top
Assign to the left node and recur
if rootleft
arrtop;
printCodesrootleft, arr, top ;
Assign to the right node and recur
if rootright
arrtop;
printCodesrootright, arr, top ;
If this is a leaf node, then we print rootdata
We also print the code for this character from arr
if rootleft && rootright
cout rootdata ;
for int i ; i top; i
cout arri;
cout endl;
void HuffmanCodeschar data int freq int size
Declaring priority queue using custom comparator
priorityqueue, Compare pq;
Populating the priority queue
for int i ; i size; i
HuffmanTreeNode newNode new HuffmanTreeNodedatai freqi;
pqpushnewNode;
Generate Huffman Encoding Tree and get the root node
HuffmanTreeNode root generateTreepq;
Print Huffman Codes
int arrMAXSIZE top ;
printCodesroot arr, top;
int main
char dataabcdef;
int freq;
int size sizeofdata sizeofdata;
HuffmanCodesdata freq, size;
return ;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
