I am having trouble building my structure of the Huffman tree when decoding.
Right now I am encoding the tree by if it has children making the prefix 0
and if it has no child make it 1
.
For example, a tree like (a,b,c,d)
would be encoded as 001a1b01c1d
and their Huffman code is
00|01|10|11
Note: |
was added for clarity and is not actually in the header.
Here’s the tree in a graphical form:
/ \
/\ /\
a b c d
Right now when I am trying to rebuild the tree using 001a1b01c1d
, The problem I am having trouble is recreating the tree properly because I am unsure what to check for when going back up to the tree (how far to go up).
Here is the code the index was only added just to try the word 'random' obviously it doesn't work for other cases. I am thinking of using the depth of the tree somehow
void Tree::build(std::queue<char> encodedHeader) {
char currentChar;
this -> thisRoot = new HCNode(0, '\0',0,0,0);
HCNode * newRoot = new HCNode (0,'\0',0,0,0);
HCNode * childZero = new HCNode (0, '\0', 0,0,0);
HCNode * childOne = new HCNode (0, '\0', 0,0,0);
childZero -> p = newRoot;
childOne -> p = newRoot;
newRoot -> c0 = childZero;
newRoot -> c1 = childOne;
this -> foreverRoot = newRoot;
while(!header.empty()) {
currentChar = header.front();
header.pop();
if(currentChar != '\n') {
if (currentChar == '0') {
HCNode * childZero = new HCNode (0, '\0', 0,0,0);
HCNode * childOne = new HCNode (0, '\0', 0,0,0);
child0 -> p = newRoot;
child1 -> p = newRoot;
newRoot -> c0 = childZero;
newRoot -> c1 = childOne;
currentChar = header.front();
while (currentChar == '0') {
newRoot = newRoot -> c0;
header.pop();
currentChar = header.front();
HCNode * childZero = new HCNode (0, '\0', 0,0,0);
HCNode * childOne = new HCNode (0, '\0', 0,0,0);
childZero -> p = newRoot;
childOne -> p = newRoot;
newRoot -> c0 = childZero;
newRoot -> c1 = childOne;
}
}
else {
currentChar = header.front();
header.pop();
if(newRoot -> c0 != NULL) {
newRoot -> c0 -> symbol = currentChar;
newRoot = newRoot -> c1;
}
else {
newRoot -> symbol = currentChar;
while(newRoot -> p != NULL && index != 2) {
index++;
newRoot = newRoot -> p;
}
index = 0;
newRoot = newRoot -> c1;
}
}
}
}