Huffman coding (C++)
Notes
#include <iostream>
using namespace std;
// Abstract superclass representing all tree nodes
class TreeNode
{
private:
int freq;
public:
virtual void printHuffmanTree(int path[], int depth) = 0;
};
// Node that consists of a simple character
class SimpleNode : public TreeNode
{
private:
char ch;
// INHERITS: int freq;
public:
virtual void printHuffman(int path[], int depth);
SimpleNode(char c, int frequency);
// INHERITS: virtual void printHuffmanTree() = 0;
};
// Node that consists of two other nodes, possibly simple characters
class CompoundNode : public TreeNode
{
private:
TreeNode * left;
TreeNode * right;
// INHERITS: int freq;
public:
virtual void printHuffmanTree(int path[], int depth);
CompoundNode(TreeNode * l, TreeNode * r, int frequency);
// INHERITS: virtual void printHuffmanTree() = 0;
};
// Constructor for simple node
SimpleNode::SimpleNode(char c, int frequency)
{
freq = frequency;
ch = c;
}
// Print out the contents of the huffman tree for this leaf node
void SimpleNode::printHuffmanTree(int path[], int depth)
{
cout << ch << ": ";
for (int i = 0; i < depth; i++) {
cout << path[i];
}
cout << endl;
}
// Constructor for compound node
CompoundNode::CompoundNode(TreeNode * l, TreeNode * r, int frequency)
{
left = l;
right = r;
freq = frequency;
}
// Print out the contents of the huffman tree starting at this node
void CompoundNode::printHuffmanTree(int path[], int depth)
{
path[depth] = 0;
left->printHuffmanTree(path, depth+1);
path[depth] = 1;
right->printHuffmanTree(path, depth+1);
}
/*
(69)
0/ \1
/ \
(26) (43)
0/ \1 0/ \1
/ | | \
o|14 i|12 e|25 (18)
0/ \1
/ \
a|10 u|8
o 00 a 110
i 01 u 111
e 10
__Tree Node__
/ \
Simple Node Complex Node
Tree Node:
simple char ch
nodes int freq
compound int freq
nodes TreeNode * left
TreeNode * right
writeHuffmanCodes()
*/