• Source
    1. #include <iostream>
    2. #include <unordered_map>
    3. #include <queue>
    4. #include <vector>
    5. using namespace std;
    6.  
    7. // Node structure for Huffman Tree
    8. struct Node {
    9. char ch;
    10. int freq;
    11. Node *left, *right;
    12. Node(char ch, int freq, Node* left = nullptr, Node* right = nullptr) {
    13. this->ch = ch;
    14. this->freq = freq;
    15. this->left = left;
    16. this->right = right;
    17. }
    18. };
    19.  
    20. // Custom comparator to make min-heap
    21. struct Compare {
    22. bool operator()(Node* a, Node* b) {
    23. return a->freq > b->freq;
    24. }
    25. };
    26.  
    27. // Recursive function to generate Huffman Codes
    28. void buildCodes(Node* root, string code, unordered_map<char, string>& huffCode) {
    29. if (!root) return;
    30. // If it's a leaf node
    31. if (!root->left && !root->right) {
    32. huffCode[root->ch] = code;
    33. return;
    34. }
    35. buildCodes(root->left, code + "0", huffCode);
    36. buildCodes(root->right, code + "1", huffCode);
    37. }
    38.  
    39. int main() {
    40. string input;
    41. cout << "Enter the string: ";
    42. cin >> input;
    43. // Step 1: Count frequency of each character
    44. unordered_map<char, int> freq;
    45. for (char ch : input) {
    46. freq[ch]++;
    47. }
    48. // Step 2: Create priority queue (min-heap) of Nodes
    49. priority_queue<Node*, vector<Node*>, Compare> pq;
    50. for (auto it : freq) {
    51. Node* newNode = new Node(it.first, it.second);
    52. pq.push(newNode);
    53. }
    54. // Step 3: Build Huffman Tree
    55. while (pq.size() > 1) {
    56. Node* node1 = pq.top(); pq.pop();
    57. Node* node2 = pq.top(); pq.pop();
    58. Node* parent = new Node('\0', node1->freq + node2->freq, node1, node2);
    59. pq.push(parent);
    60. }
    61. Node* root = pq.top(); // Final root of Huffman Tree
    62. // Step 4: Generate Huffman Codes
    63. unordered_map<char, string> huffCode;
    64. buildCodes(root, "", huffCode);
    65. // Step 5: Display Huffman Codes
    66. cout << "\nHuffman Codes:\n";
    67. for (auto pair : huffCode) {
    68. cout << pair.first << " → " << pair.second << endl;
    69. }
    70. return 0;
    71. }
    72.