#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
#include <string>
using namespace std;
struct Node {
char ch;
int freq;
Node *left, *right;
Node(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
};
struct Compare {
bool operator()(Node* l, Node* r) {
return l->freq > r->freq; // min-heap by freq
}
};
void buildCodes(Node* root, const string& str, unordered_map<char, string>& huffmanCode) {
if (!root) return;
if (!root->left && !root->right) {
huffmanCode[root->ch] = str; // leaf node code assignment
}
buildCodes(root->left, str + "0", huffmanCode); // left edge adds 0
buildCodes(root->right, str + "1", huffmanCode); // right edge adds 1
}
void huffmanEncoding(const unordered_map<char, int>& freq) {
priority_queue<Node*, vector<Node*>, Compare> pq;
for (auto pair : freq) {
pq.push(new Node(pair.first, pair.second)); // create leaf nodes
}
while (pq.size() != 1) {
Node* left = pq.top(); pq.pop(); // smallest freq
Node* right = pq.top(); pq.pop(); // second smallest freq
Node* sum = new Node('\0', left->freq + right->freq); // internal node
sum->left = left; // left child
sum->right = right; // right child
pq.push(sum); // push combined node back
}
Node* root = pq.top();
unordered_map<char, string> huffmanCode;
buildCodes(root, "", huffmanCode); // generate codes
for (auto pair : freq) {
cout << pair.first << ":" << huffmanCode[pair.first] << "\n";
}
}
int main() {
unordered_map<char, int> freq = {{'a',5}, {'b',9}, {'c',12}, {'d',13}, {'e',16}, {'f',45}};
huffmanEncoding(freq);
return 0;
}
pq.push(new Node(pair.first, pair.second));
create leaf nodes for each character with frequency
Node* left = pq.top(); pq.pop();
extract smallest frequency node
Node* right = pq.top(); pq.pop();
extract second smallest frequency node
Node* sum = new Node('\0', left->freq + right->freq);
create internal node with combined frequency
sum->left = left; sum->right = right;
assign children to internal node
push combined node back to priority queue
buildCodes(root, "", huffmanCode);
recursively assign codes by traversing tree
if (!root->left && !root->right) { huffmanCode[root->ch] = str; }
assign code string to leaf node character
a:1100
b:1101
c:100
d:101
e:111
f:0