1+ // File: Algorithms/Greedy/huffman_coding.cpp
2+ // Algorithm: Huffman Coding
3+ // Category: Greedy Algorithm
4+ // Difficulty: Medium (Intermediate)
5+ // Description: Builds a Huffman Tree to assign variable-length codes to characters
6+ // based on their frequencies, minimizing the total encoding length.
7+
18#include < iostream>
2- #include < string>
39#include < queue>
10+ #include < unordered_map>
411#include < vector>
5- #include < map>
612
713using namespace std ;
814
9- struct MinHeapNode
10- {
11- char data;
12- unsigned freq;
13- MinHeapNode *left, *right;
15+ // 🧠 Node structure for Huffman Tree
16+ struct Node {
17+ char ch; // Character
18+ int freq; // Frequency of the character
19+ Node *left; // Left child
20+ Node *right; // Right child
1421
15- MinHeapNode (char data, unsigned freq)
16- {
22+ Node (char character, int frequency) {
23+ ch = character;
24+ freq = frequency;
1725 left = right = nullptr ;
18- this ->data = data;
19- this ->freq = freq;
2026 }
2127};
2228
23- struct compare
24- {
25- bool operator ()(MinHeapNode *l, MinHeapNode *r)
26- {
27- return (l->freq > r->freq );
29+ // ⚡ Custom comparator for priority queue (min-heap)
30+ struct Compare {
31+ bool operator ()(Node* a, Node* b) {
32+ return a->freq > b->freq ; // Smaller frequency gets higher priority
2833 }
2934};
3035
31- void printCodes (struct MinHeapNode *root, string str)
32- {
33- if (!root)
34- return ;
36+ // 📌 Recursive function to generate Huffman Codes
37+ void generateCodes (Node* root, string code, unordered_map<char , string>& huffmanCode) {
38+ if (!root) return ;
3539
36- if (root->data != ' $' )
37- cout << root->data << " : " << str << " \n " ;
40+ // Leaf node -> store the code
41+ if (!root->left && !root->right ) {
42+ huffmanCode[root->ch ] = code;
43+ }
3844
39- printCodes (root->left , str + " 0" );
40- printCodes (root->right , str + " 1" );
45+ generateCodes (root->left , code + " 0" , huffmanCode );
46+ generateCodes (root->right , code + " 1" , huffmanCode );
4147}
4248
43- void HuffmanCodes (string text)
44- {
45- map<char , unsigned > freq;
46- for (char c : text)
47- {
48- freq[c]++;
49+ // 🌳 Build Huffman Tree and encode
50+ void buildHuffmanTree (const string& text) {
51+ // Step 1: Count frequency of each character
52+ unordered_map<char , int > freq;
53+ for (char ch : text) {
54+ freq[ch]++;
55+ }
56+
57+ // Step 2: Create a min-heap (priority queue) of leaf nodes
58+ priority_queue<Node*, vector<Node*>, Compare> pq;
59+
60+ for (auto pair : freq) {
61+ pq.push (new Node (pair.first , pair.second ));
4962 }
5063
51- priority_queue<MinHeapNode *, vector<MinHeapNode *>, compare> minHeap;
64+ // Step 3: Merge two lowest frequency nodes until one node remains
65+ while (pq.size () > 1 ) {
66+ Node* left = pq.top (); pq.pop ();
67+ Node* right = pq.top (); pq.pop ();
5268
53- for (auto pair : freq)
54- {
55- minHeap.push (new MinHeapNode (pair.first , pair.second ));
69+ Node* merged = new Node (' \0 ' , left->freq + right->freq );
70+ merged->left = left;
71+ merged->right = right;
72+ pq.push (merged);
5673 }
5774
58- MinHeapNode *left, *right, *top;
75+ // Step 4: Generate Huffman Codes by traversing the tree
76+ Node* root = pq.top ();
77+ unordered_map<char , string> huffmanCode;
78+ generateCodes (root, " " , huffmanCode);
79+
80+ cout << " \n Huffman Codes for each character:\n " ;
81+ for (auto pair : huffmanCode) {
82+ cout << pair.first << " : " << pair.second << endl;
83+ }
5984
60- while (minHeap.size () != 1 )
61- {
62- left = minHeap.top ();
63- minHeap.pop ();
85+ // Step 5: Encode the input string
86+ string encodedString = " " ;
87+ for (char ch : text) {
88+ encodedString += huffmanCode[ch];
89+ }
6490
65- right = minHeap. top () ;
66- minHeap. pop () ;
91+ cout << " \n Original string: " << text << endl ;
92+ cout << " Encoded string : " << encodedString << endl ;
6793
68- top = new MinHeapNode (' $' , left->freq + right->freq );
69- top->left = left;
70- top->right = right;
94+ // (Optional) Step 6: Decoding - to verify correctness
95+ string decodedString = " " ;
96+ Node* curr = root;
97+ for (char bit : encodedString) {
98+ if (bit == ' 0' ) curr = curr->left ;
99+ else curr = curr->right ;
71100
72- minHeap.push (top);
101+ if (!curr->left && !curr->right ) {
102+ decodedString += curr->ch ;
103+ curr = root;
104+ }
73105 }
74106
75- cout << " Huffman Codes for the text:\n " ;
76- printCodes (minHeap.top (), " " );
107+ cout << " Decoded string : " << decodedString << endl;
77108}
78109
79- int main ()
80- {
81- string str = " huffman coding is a greedy algorithm" ;
82- HuffmanCodes (str);
110+ // 🧪 Main function to test Huffman Coding
111+ int main () {
112+ string text;
113+ cout << " Enter a string to encode using Huffman Coding: " ;
114+ getline (cin, text);
115+
116+ buildHuffmanTree (text);
83117 return 0 ;
84- }
118+ }
119+
120+
121+ // added to main branch
0 commit comments