解码时,我无法构建哈夫曼树的结构。霍夫曼解码算法
现在我正在编码的树,如果它有子码使前缀0
,如果它没有孩子使它1
。
例如,像(a,b,c,d)
树会被编码为001a1b01c1d
及其Huffman编码是
00|01|10|11
注:|
是为清晰添加的,实际上并不是在头中。
这里的图形形式的树:
/\
/\ /\
a b c d
现在,当我试图重建使用001a1b01c1d
树,我有麻烦的问题是重新创建树正确,因为我不能确定检查什么当回到树上时(走多远)。
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;
}
}
}
}
我猜如果你的代码有问题,你至少应该显示它的一部分。否则,我们如何才能通过[tag:C++]代码获得帮助?你想最终单独标记[tag:algorithm]? – 2014-10-28 19:32:40
在构建树之前,或者尝试对算法进行编码之前,应首先了解为什么需要这样做以及代表什么。 http://www.youtube.com/results?search_query=computerphile+huffman – user2485710 2014-10-28 19:40:51
我会说走到下一个正确的孩子。但是你的树编码方法似乎很奇怪。 – Jarod42 2014-10-28 19:41:33