霍夫曼编码创建树C++

Huffman Coding Creating Tree C++

本文关键字:C++ 创建 编码 霍夫曼      更新时间:2023-10-16

代码是更大解决方案的一部分。当我在 prioriQueue 中只有一个元素时,lastLeft 和 lastRight 是 nullptr。知道如何更改此算法以仅与一个元素一起工作,或者一些技巧如何更好地编写它吗?问题与评论"这是一个问题"一致。

 std::shared_ptr<Leaf> HUFFMAN::TreeGenerating()
    {
        std::shared_ptr<Leaf> lastLeft = nullptr; // addr of last left child
        std::shared_ptr<Leaf> lastRight = nullptr; // addr of last right child
        while (!prioriQueue.empty())
        {
            std::shared_ptr<Leaf> rightChild = std::make_shared<Leaf>();
            std::shared_ptr<Leaf> leftChild = std::make_shared<Leaf>();
            std::shared_ptr<Leaf> nRoot = std::make_shared<Leaf>();
            if (prioriQueue.size() == 1) // getting last element from prioriQueue, this if end algorithm
            {
                *nRoot = getElement();
                nRoot->setLeftChild(lastLeft);
                nRoot->setRightChild(lastRight);
                nRoot->setFreq(lastLeft->getFreq() + lastRight->getFreq()); // HERE IS A PROBLEM !!
                nRoot->setValue(0);
                return nRoot;
            }
            else 
            {
                *leftChild = getElement();
                *rightChild = getElement();
                nRoot->setLeftChild(leftChild);
                nRoot->setRightChild(rightChild);
                nRoot->setFreq(leftChild->getFreq() + rightChild->getFreq());
                nRoot->setValue(0);
                lastLeft = leftChild;
                lastRight = rightChild;
                InsertIntoQueue(*nRoot);
            }
        }
}

我会把它作为评论删除,因为 OP 的问题缺少太多信息以获得正确的答案,但它对于评论来说太复杂了。请注意,代码完全未经测试,因为需要太多假设。

OP已经大大复杂了。所需要的只是类似

std::shared_ptr<Leaf> HUFFMAN::TreeGenerating()
{
    if (!prioriQueue.empty())
    {
        while (prioriQueue.size() > 1)
        {
            std::shared_ptr<Leaf> node = std::make_shared<Leaf>(getElement(), 
                                                                getElement());
            InsertIntoQueue(node);
        }
        return (getElement());
    }
    else
    {
        // handle the empty case
    }
}

Leaf 构造函数类似如下:

Leaf::Leaf(std::shared_ptr<Leaf> right, 
           std::shared_ptr<Leaf> left)
{
    rightChild = right;
    leftChild = left;
    freq = right->freq + left->freq
}

或使用成员初始值设定项列表

Leaf::Leaf(std::shared_ptr<Leaf> right, 
           std::shared_ptr<Leaf> left):
    rightChild(right),
    leftChild(left),
    freq(right->freq + left->freq)
{
}

我还强烈建议重新考虑这种滥用std::shared_ptr