霍夫曼树错误地插入/检索值

问题描述

在霍夫曼编码和解码的c ++实现中,尝试解码和输出结果时,我始终收到奇怪的输出。例如,给定输入:

11 00001 01 11 101 01 11 1001 01 101 1000 01 00000 0011 00101 01 11 101 01 11 1001 01 00100 00011 01 101 1000 01 00010 0011

从理论上讲,它应该解码为“是否存在,取决于我自己”,但我却收到“ if,isefbe,ismfttofp”

还有其他一些测试用例返回的结果也都是奇数,但我认为特定的结果没有用,除了我非常确定自己插入霍夫曼树的实现在某种程度上是不正确的事实之外,

但是,值得注意的是,我收到的任何结果都没有包含空格。

霍夫曼树的代码

void huffmanTree(huffmanNode *n,string prefix,char letter) {
    if (prefix.length() == 0) {
        n->character = letter;
    }
    if (prefix[0] == '0') {
        if (n->left == NULL) {
            n->left = new huffmanNode(0,'\0');
        }
        huffmanTree(n->left,prefix.substr(1,prefix.length()-1),letter);
    } else if (prefix[0] == '1') {
        if (n->right == NULL) {
            n->right = new huffmanNode(0,'\0');
        }
        huffmanTree(n->right,letter);
    }
}

问题也可能出在我的遍历上,

char buffer[256];
huffmanNode *n = new huffmanNode(0,'\0');

while (true) {
    char first = file.get();
    if ((first == '\n') || (first == '\r')) {
        continue;
    }
    
    char second = file.get();
    if ((first == '-') && (second == '-')) {
        file.getline(buffer,255,'\n');
        break;
    }
    file.getline(buffer,'\n');
        
    string prefixCode = string(buffer);
    huffmanTree(n,prefixCode,first);
}
    
huffmanNode *n1 = n;
char bit;
    
while ((bit = file.get()) != '-') {
    if ((bit != '0') && (bit != '1')) {
        continue;
    }
    if (n1->left != NULL && bit == '0') {
        n1 = n1->left;
    }
    if (n1->right != NULL && bit == '1') {
        n1 = n1->right;
    }
    if (n1->left == NULL && n1->right == NULL) {
        cout << n1->getChar();
        n1 = n;
    }
}

是否有一些明显的东西导致我失踪了?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)