-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHuffman.cpp
More file actions
75 lines (56 loc) · 1.72 KB
/
Huffman.cpp
File metadata and controls
75 lines (56 loc) · 1.72 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
73
74
75
#include "Huffman.h"
//My partner is Chris Alonzo - calonzo@bu.edu
void Huffman::buildHuffmanTree(char characters[], int frequency[], int size)
{
node* left, * right, * top;
for (int i = 0; i < size; ++i)
this->minHeap.push(new node(characters[i], frequency[i]));
while (this->minHeap.size() != 1) {
left = this->minHeap.top();
this->minHeap.pop();
right = this->minHeap.top();
this->minHeap.pop();
top = new node(NULL, left->frequency + right->frequency);
top->left = left;
top->right = right;
this->minHeap.push(top);
}
}
void Huffman::printCodes()
{
cout << "Huffman Code\t Character" << endl;
cout << "----------------------------------" << endl;
this->printHuffmanCodes(this->minHeap.top(), "");
}
void Huffman::decodeText(string filename)
{
string encodedText;
ifstream encodedFile(filename);
getline(encodedFile, encodedText);
encodedFile.close();
string decodedText = "";
struct node* temp = this->minHeap.top();
for (int i = 0; i < encodedText.size(); i++)
{
if (encodedText[i] == '0')
temp = temp->left;
else
temp = temp->right;
if (temp->left == NULL && temp->right == NULL)
{
decodedText += temp->data;
temp = minHeap.top();
}
}
decodedText += '\0';
cout << endl << "The decoded text is: " << decodedText;
}
void Huffman::printHuffmanCodes(node* root, string str)
{
if (!root)
return;
if (root->left == NULL && root->right == NULL)
cout << str << "\t\t\t" << root->data << "\n";
printHuffmanCodes(root->left, str + "0");
printHuffmanCodes(root->right, str + "1");
}