-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHuffmanTree.cpp
60 lines (51 loc) · 1.37 KB
/
HuffmanTree.cpp
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
#include "HuffmanTree.h"
#include <iostream>
#include <memory>
#include <string>
#include <sstream>
#include <fstream>
#include <typeinfo>
#include <tr1/unordered_map>
using namespace std::tr1;
using namespace std;
HuffmanTree::HuffmanTree(){
}
HuffmanTree::HuffmanTree(string filename){
readCharacters(filename);
for(auto character: frequencyMap){
shared_ptr<HuffmanNode> node(make_shared<HuffmanNode>());
node->setKey(character.first);
node->setValue(character.second);
queue.push(node);
}
}
void HuffmanTree::readCharacters(string filename){
char ch;
fstream fin(filename+".txt", fstream::in);
while (fin >> noskipws >> ch){
auto find = frequencyMap.find(ch); //find the search for the character in the map
characters.push_back(ch);
//if the character is in the map already, increment its value
if(find != frequencyMap.end()){
find -> second++;
}else{
frequencyMap.insert({ch, 1});
}
}
}
bool HuffmanTree::buildTree(){
while(queue.size() > 1){
shared_ptr<HuffmanNode> node1;
node1 = queue.top();
queue.pop();
shared_ptr<HuffmanNode> node2;
node2 = queue.top();
queue.pop();
shared_ptr<HuffmanNode> parent(make_shared<HuffmanNode>());
parent->setValue(node1->getValue() + node2->getValue());
parent->setLeft(node1);
parent->setRight(node2);
queue.push(parent);
}
return false;
}