-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhuffman_utility.cpp
40 lines (31 loc) · 1.03 KB
/
huffman_utility.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
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <queue>
#include "huffman_utility.h"
huffmanNode *buildHuffmanTree(map<char, int> &freqMap)
{
priority_queue<huffmanNode *, vector<huffmanNode *>, bool (*)(huffmanNode *, huffmanNode *)> maxHeap(huffmanNode::compareHuffmanNodes);
// add all elements of freqMap to priority queue as huffmanNodes
for (pair<char, int> element : freqMap)
{
char character = element.first;
int frequency = element.second;
huffmanNode *node = new huffmanNode(character, frequency);
maxHeap.push(node);
}
while (maxHeap.size() > 1)
{
huffmanNode *rightNode = maxHeap.top();
maxHeap.pop();
huffmanNode *leftNode = maxHeap.top();
maxHeap.pop();
int totalFreq = leftNode->frequency + rightNode->frequency;
huffmanNode *node = new huffmanNode('\0', totalFreq);
node->left = leftNode;
node->right = rightNode;
maxHeap.push(node);
}
return maxHeap.top();
}