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

时间:2013-03-07 01:23:49

标签: c++

我创建了一个霍夫曼树并且看起来是正确的,但是在遍历数据结构时我很弱。我根据我的根树中包含的信息在纸上绘制了树,看起来很好,但是我的代码有问题,我不知道要修复它。

第一个0是持续存在的,每次我采取正确的,它似乎在追加0之后。

example:
L: 01
H: 1111

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

代码段

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已解决:我发现code.append();功能搞砸了。我改了它代码+“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");
    }
}

1 个答案:

答案 0 :(得分:1)

你错过了else s:

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);
    }
}