1

我创建了一个霍夫曼树,它似乎是正确的,但是在遍历数据结构方面我很弱。我根据根树中包含的信息在纸上画出了树,它看起来很好,但是我的代码有问题,我不知道如何修复它。

第一个 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);
    }
}

更新已解决:我发现 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");
    }
}
4

1 回答 1

1

你错过了elses:

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);
    }
}
于 2013-03-07T01:30:09.003 回答