简体   繁体   English

需要帮助穿越一棵树; 霍夫曼编码

[英]Need help traversing a tree; Huffman Coding

I have created a Huffman Tree and It appears to be correct, however I am weak when it comes to traversing data structures. 我已经创建了一个霍夫曼树,它看起来是正确的,但是在遍历数据结构时我很虚弱。 I drew out the Tree on paper based on the information contained in my root tree and it appears to be well, however My code is faulty and I do not know hot to fix it. 我根据根目录树中包含的信息在纸上绘制了该目录树,它看起来不错,但是我的代码有错误,我不知道要对其进行修复。

The first 0 is persisting and, every time i take right, it seems to append a 0 after. 第一个0持续存在,每当我正确时,它似乎都在后面附加一个0。

example:
L: 01
H: 1111

but my traversal gives me:
L: 001
H: 01010101

code Snippets 代码片段

struct node
{
int symbol;
int frequency;
node* left;
node* right;
};

void Huffman::generateCode(node *tree, std::string code)
{
    if(tree->left == NULL && tree->right == NULL)
    {
        //std::cout << "Leaf Found: " << tree->symbol << "\t" << code << std::endl;
        mapCode.insert(std::pair<int, std::string>(tree->symbol,code));
    }
    if(tree->left != NULL)
    {
        code.append("0");
        generateCode(tree->left, code);
    }
    if(tree->right != NULL)
    {
        code.append("1");
        generateCode(tree->right, code);
    }
}

UPDATE SOLVED: i figure out that the code.append(); 解决了的问题:我发现code.append(); function was messing it up. 功能搞砸了。 i changed it too code + "0"; 我也更改了代码+“ 0”;

void Huffman::generateCode(node *tree, std::string code)
{
    if(tree->left == NULL && tree->right == NULL)
    {
        std::cout << "Leaf Found: " << tree->symbol << "\t" << code << std::endl;
        mapCode.insert(std::pair<int, std::string>(tree->symbol,code));
    }
    if(tree->left != NULL)
    {
        generateCode(tree->left, code + "0");
    }
    if(tree->right != NULL)
    {
        generateCode(tree->right, code + "1");
    }
}

you missed the else s: 您错过了else

void Huffman::generateCode(node *tree, std::string code)
{
    if(tree->left == NULL && tree->right == NULL)
    {
        //std::cout << "Leaf Found: " << tree->symbol << "\t" << code << std::endl;
        mapCode.insert(std::pair<int, std::string>(tree->symbol,code));
    }
    else if(tree->left != NULL)
    {
        code.append("0");
        generateCode(tree->left, code);
    }
    else if(tree->right != NULL)
    {
        code.append("1");
        generateCode(tree->right, code);
    }
}

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

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