-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhuffmanTree.cpp
More file actions
64 lines (47 loc) · 1.16 KB
/
huffmanTree.cpp
File metadata and controls
64 lines (47 loc) · 1.16 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
#include "huffmanTree.h"
huffmanTree::huffmanTree(unordered_map<char,int>histogram)
{
unordered_map<char,int>::iterator it;
//Store all nodes in a minheap descending order
for(it = histogram.begin(); it != histogram.end(); it++)
{
if(it->second != 0)
minHeap.push(new huffmanNode(it->first,it->second,false));
}
}
void huffmanTree::buildHuffmanTree()
{
while(minHeap.size() != 1)
{
//Construct tree by joining two top nodes
left = minHeap.top();
minHeap.pop();
right = minHeap.top();
minHeap.pop();
//Push newly created node as internal node into min heap
top = new huffmanNode(' ',left->frequency + right->frequency,true);
top->left = left;
top->right = right;
minHeap.push(top);
}
}
huffmanNode* huffmanTree::getRoot()
{
return minHeap.top();
}
void huffmanTree::generateCodes(huffmanNode *root, string code)
{
//Pre order traversal generates codes for tree
if(root == NULL)
return;
if(!root->isInternalNode)
{
huffmanCodes[root->data] = code;
}
generateCodes(root->left,code + "0");
generateCodes(root->right,code + "1");
}
unordered_map<char,string> huffmanTree:: getHuffmanCodes()
{
return huffmanCodes;
}