-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHuffman tree.cpp
More file actions
72 lines (54 loc) · 1.75 KB
/
Huffman tree.cpp
File metadata and controls
72 lines (54 loc) · 1.75 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <queue>
#include <vector>
#include <unordered_map>
using namespace std;
struct HuffmanNode {
char data;
int frequency;
HuffmanNode* left;
HuffmanNode* right;
HuffmanNode(char c, int freq) : data(c), frequency(freq), left(nullptr), right(nullptr) {}
};
struct CompareNodes {
bool operator()(HuffmanNode* left, HuffmanNode* right) {
return left->frequency > right->frequency;
}
};
HuffmanNode* buildHuffmanTree(const string& S, const vector<int>& f) {
priority_queue<HuffmanNode*, vector<HuffmanNode*>, CompareNodes> minHeap;
for (int i = 0; i < S.size(); ++i) {
minHeap.push(new HuffmanNode(S[i], f[i]));
}
while (minHeap.size() > 1) {
HuffmanNode* left = minHeap.top();
minHeap.pop();
HuffmanNode* right = minHeap.top();
minHeap.pop();
HuffmanNode* newNode = new HuffmanNode('$', left->frequency + right->frequency);
newNode->left = left;
newNode->right = right;
minHeap.push(newNode);
}
return minHeap.top();
}
void printHuffmanCodes(HuffmanNode* root, string code, unordered_map<char, string>& huffmanCodes) {
if (root == nullptr) {
return;
}
if (!root->left && !root->right) {
cout << " " << root->data << " : " << code << endl;
huffmanCodes[root->data] = code;
}
printHuffmanCodes(root->left, code + "0", huffmanCodes);
printHuffmanCodes(root->right, code + "1", huffmanCodes);
}
int main() {
string S = "abcdef";
vector<int> f = {5, 9, 12, 13, 16, 45};
HuffmanNode* root = buildHuffmanTree(S, f);
unordered_map<char, string> huffmanCodes;
cout << "Huffman codes will be:" << endl;
printHuffmanCodes(root, "", huffmanCodes);
return 0;
}