I do not understand this implementation of the Huffman algorithm

    template<class T>
    void huffman(MinHeap<TreeNode<T>*> heap, int n)
    {
      for(int i=0;i<n-1;i++)
      {
        TreeNode<T> *first = heap.pop();
        TreeNode<T> *second = heap.pop();
        TreeNode<T> *bt = new BinaryTreeNode<T>(first, second, first.data, second.data);
        heap.push(bt);
      }
    }

In my Basics of Data Structures in C ++, the tutorial gave a 2-page definition of Huffman coding and the code above. For me, the book was not detailed enough, so I did a search on Google and I found out how the Huffman coding process works. The tutorial states that at the end of the above code, a Huffman tree is created. But to me, this seems wrong, because the Huffman tree is not necessarily a complete tree, but the code seems to always give a full tree because of heap.push(). So can someone explain to me how this piece of code is not wrong?

+3
source share
2

- , , node. , node node. .

+5

, . ( MinHeap ), "" node, . , node . ; , , , - .

, , , , . , "n"; while (heap.size() > 1). , "", , .

0

Source: https://habr.com/ru/post/1755069/


All Articles