Greedy Algorithms8 sections · 316 units
Open in Course

Huffman - Algorithm

Build the tree

Huffman's greedy algorithm:

1.1. Create a leaf node for each character with its frequency.

2.2. Put all nodes in a min-heap (by frequency).

3.3. While heap has more than 11 node:

  • Extract two minimum frequency nodes.
  • Create a new internal node with these as children.
  • Insert the new node with frequency = sum.

4.4. The remaining node is the root. Edges to left are 00, to right are 11. A character's code is the path from root to leaf. Time: O(nlogn)O(n \log n). Space: O(1)O(1).