-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhuffman_code.cpp
More file actions
45 lines (36 loc) · 1.12 KB
/
huffman_code.cpp
File metadata and controls
45 lines (36 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include "huffman_code.h"
#include <queue>
auto Huffman::HuffmanCode(const std::map<int, char>& freq_map) -> HuffmanNode*
{
std::priority_queue<HuffmanNode*, std::vector<HuffmanNode*>, MinComparator> min_queue;
for (auto [freq, ch] : freq_map)
{
min_queue.push(new HuffmanNode{freq, ch, freq});
}
while (static_cast<int>(min_queue.size()) != 1)
{
const auto left = min_queue.top();
min_queue.pop();
const auto right = min_queue.top();
min_queue.pop();
const int key = left->key + right->key;
auto node = new HuffmanNode{key, '-', left->freq + right->freq};
node->left = left;
node->right = right;
min_queue.push(node);
}
return min_queue.top();
}
void Huffman::TraversalHuffmanCode(const HuffmanNode* root, const std::string& code, std::map<char, std::string>& result)
{
if (root == nullptr)
{
return;
}
if (root->ch != '-')
{
result.insert(std::pair(root->ch, code));
}
TraversalHuffmanCode(root->left, code + "0", result);
TraversalHuffmanCode(root->right, code + "1", result);
}