The code is a part of bigger solution. When I have only one element in prioriQueue, lastLeft and lastRight are nullptr. Any idea how to change this algorithm to work corectly with only one element, or some tips how to write it better? Problem is in line with comment "HERE IS A PROBLEM".
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);
}
}
}