Advertisement
Adam_mz_

Untitled

Jan 14th, 2022
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <iostream>
  2. #include <set>
  3. #include <sstream>
  4.  
  5. class HuffmanNode
  6. {
  7. public:
  8.  
  9.     char letter; // '\0' for non-leaf nodes
  10.     int freq;
  11.  
  12.     HuffmanNode *leftChild;
  13.     HuffmanNode *rightChild;
  14.  
  15.     HuffmanNode(char letter, int freq, HuffmanNode *leftChild = nullptr, HuffmanNode *rightChild = nullptr)
  16.             : letter(letter), freq(freq), leftChild(leftChild), rightChild(rightChild)
  17.     {}
  18.  
  19.     HuffmanNode(const HuffmanNode &node)
  20.             : letter(node.letter), freq(node.freq), leftChild(node.leftChild), rightChild(node.rightChild)
  21.     {}
  22.  
  23.     bool operator<(const HuffmanNode &node) const
  24.     {
  25.         return this->freq <= node.freq;
  26.     }
  27. };
  28.  
  29.  
  30. void huffmanCode(std::multiset<HuffmanNode> &multiset)
  31. {
  32.     while (multiset.size() > 1)
  33.     {
  34.         HuffmanNode *n1 = new HuffmanNode(*(multiset.begin()));
  35.         multiset.erase(multiset.begin());
  36.         HuffmanNode *n2 = new HuffmanNode(*(multiset.begin()));
  37.         multiset.erase(multiset.begin());
  38.  
  39.  
  40.         multiset.insert(HuffmanNode('\0', n1->freq + n2->freq, n1, n2));
  41.     }
  42.  
  43. }
  44.  
  45. void postOrderPrint(HuffmanNode *node, const std::string &s)
  46. {
  47.     if (!node)
  48.         return;
  49.     postOrderPrint(node->leftChild, s + "0");
  50.     postOrderPrint(node->rightChild, s + "1");
  51.  
  52.     if (node->letter != '\0')
  53.         std::cout << node->letter << ": " << s << "\n";
  54. }
  55.  
  56. int main()
  57. {
  58.     std::multiset<HuffmanNode> s = {
  59.                                     {'D', 1},
  60.                                     {'C', 1},
  61.                                     {'R', 2},
  62.                                     {'B', 2},{'A', 5}}; // for the example ABRACADABRA
  63.  
  64.     huffmanCode(s);
  65.     HuffmanNode root = *(s.begin());
  66.  
  67.    
  68.     postOrderPrint(&root, "");
  69.  
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement