Idea: Merge the two lowest-frequency nodes (leaf or internal) into a new node until every leaf has been considered.
Use a priority queue Q to keep nodes ordered by frequency.
Huffman(c) ; Analysis n = |c| ; Q is a binary heap Q = c ; O(n) BuildHeap for i = 1 to n-1 ; O(n) z = Allocate-Node() x = Extract-Min(Q) ; O(lgn) O(n) times y = Extract-Min(Q) ; O(lgn) O(n) times left(z) = x right(z) = y f(z) = f(x) + f(y) Insert(Q,z) ; O(lgn) O(n) times return Extract-Min(Q) ; ----------------- ; O(nlgn)