繁体   English   中英

霍夫曼解码树的奇怪错误

[英]strange bug with huffman decoding tree

我较早时提出了有关算法和实现的问题,但遇到了我无法解决的问题。

我能够从文本文件中提取前缀并将其放入向量中,例如:

a 0
b 100
c 101
d 11

[0, a, 1, 0, 0, b, 1, 0, 1, c, 1, 1, d]

所以我的代码:

  • 从根节点开始
  • 遍历向量。 如果我们得到0,则取当前节点,并使其左指针指向新节点。 如果得到1,则取当前节点,并使其正确的指针指向新节点。 如果是字母,则将该字符存储到当前节点并从根开始。

(一个节点仅持有一个值,并具有左右指针)

void Foo:: build(vector<char> v) {
    node* root = new node; 

    vector<char>:: iterator itr;

    node* current = root; 
    cout << " *" << endl;

    for(itr =  v.begin(); itr != v.end(); itr++) {
        cout << "(" << *itr << ")" << endl;

        if (!isdigit(*itr)) {
            current->value = *itr; 
            current = root; 
            cout << "*" << endl;
        }
        if (*itr == '0') {
            cout << "<-" << endl; 
            current->left = new node; 
            current = current->left; 
        }
        if (*itr == '1') {
            cout << "->" << endl; 
            current->right = new node; 
            current = current->right; 
        }
    }

    nodeVector.push_back(*root); 
}

如果您对couts感到好奇,则*表示根。 因此对于'a',它将从根*开始,遇到0,然后<-左移以将'a'放入该节点,然后从根*开始。 我只是这样做,看它是否像应该的那样向左和向右运动,这似乎还可以。

 *
(0)
<-
(a)
*
(1)
->
(0)
<-
(0)
<-
(b)
*
(1)
->
(0)
<-
(1)
->
(c)
*
(1)
->
(1)
->
(d)
*

我遇到的问题很奇怪。 似乎唯一起作用的字母是“ a”和“ d”。 例如, root->left->value会给我“一个”, root->right->right->value将给予“d”,但root->right->left->right->value应为'c'似乎从来没有放在节点位置。 当我尝试获取此值时,程序崩溃。 当我尝试对一串位进行解码时,该消息是错误的,因为它只能执行“ d”和“ a”。 这使我怀疑这是树的建造。 任何建议将不胜感激!

在分配新节点之前,您需要检查该路径之前是否已经分配过。 例如

if (*itr == '0') {
    cout << "<-" << endl;
    if (current->left) current = current->left;
                  else current = (current->left = new node);
}

6502是正确的。

每次您的传递循环通过时,您都在树上构造一条新路径 左边的一个很好,因为它永远不会被覆盖(但是如果您有一个节点和2个叶子而不是一个叶子,它也会失败)。 每次都会重新分配右侧的路径,并且该路径会覆盖之前创建的节点,因此只有您最后的“ d”条目可见。 换句话说,创建了“ b”和“ c”,但是每次创建新的正确条目时,指向它们的指针都会丢失(覆盖)。

正如6502指出的那样,您需要检查是否已创建该节点。 但是您的代码可能会失败,因为空指针未初始化为0,因此代码就像节点已存在一样继续进行,但实际上并没有。 每一个 new node 必须初始化空指针, leftright ,如果你打算测试它们的内容。 例如:

if (*itr == '0') {
    cout << "<-" << endl;
    if (current->left) current = current->left;
    else
    {
        current = (current->left = new node);
        current->left = 0;  // initialize your empty pointers!
        current=>right = 0; // initialize your empty pointers!
    }
}

注意,在new构造函数中放置指针初始化的更好的地方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM