At this point, we can implement the actual tree construction. While there is
more than one item on the list, we simply combine the two lowest frequency
nodes. Because of the invariant that the input list is sorted, these are just
the first and second nodes on the list. This is not the only reason for the
invariant though. When one creates the parent node, one could just append it
onto the list and resort the list. That's very algorithmically inefficient
though as Python's sorting algorithm would still take O(n*log n) time, and
even the best sorting algorithms for this particular situation would take
O(n). On the other hand, by assuming the sorted invariant, we can just do a
binary insertion, putting the list in sorted form with the new element in just
O(log n) time. This means that this list based method is just as efficient as
the typical heap based methods for Huffman tree construction. There is a
Python library that implements binary insertion, so we will include it.
