-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHuffmanTree.hpp
46 lines (35 loc) · 1.39 KB
/
HuffmanTree.hpp
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
#ifndef HUFFMANTREE_H
#define HUFFMANTREE_H
#include "HuffmanBase.hpp"
#include "HeapQueue.hpp"
#include <iostream>
#include <map>
#include <stack>
class HuffmanTree : HuffmanTreeBase {
private:
size_t n;
HuffmanNode* root;
public:
std::string compress(const std::string inputStr) override;
std::string serializeTree() const override;
std::string decompress(const std::string inputCode, const std::string serializedTree) override;
void findCode(const HuffmanNode* node, std::map<char, std::string>& codeMap, std::string code) {
if (node == nullptr)
return;
if(node->isLeaf())
codeMap[node->getCharacter()] = code;
findCode(node->left, codeMap, code + "0");
findCode(node->right, codeMap, code + "1");
}
// Helper function to recursively serialize the Huffman Tree in postorder traversal
void serialize(const HuffmanNode* node, std::string& outString) const {
if (node == nullptr) return;
serialize(node->left, outString);
serialize(node->right, outString);
// If node is a leaf
if (node->isLeaf()) outString = outString + "L" + node->getCharacter();
// If node is a branch
if (node->isBranch()) outString += "B";
}
};
#endif /*HUFFMANTREE_H*/