每次把權值最小的兩棵二叉樹合併ide
例如:1 2 3 4 5ui
生成的哈夫曼樹以下spa
咱們利用最小堆來得到兩個最小的值,並把新的節點插入堆中。 也能夠先排序,刪除兩個最小的,再把新值插入,可是效率沒有最小堆高。code
1 typedef struct TreeNode *HuffmanTree; 2 struct TreeNode{ 3 int weight; 4 HuffmanTree Left,Right; 5 } 6 HuffmanTree Huffman(MinHeap H) 7 {//假設H->Size個權值已經存在H->Elements[]->weight 8 int i; 9 HuffmanTree T; 10 BuildMinHeap(H); 11 for(i=1;i<H->Size;i++) 12 { 13 T=malloc(sizeof(struct TreeNode)); 14 T->Left=DeleteMin(H); 15 T->Right=DeleteMin(H); 16 T->weight=T->Left->weight+T->Right->weight; 17 Insert(H,T); 18 } 19 T=DeleteMin(H); 20 return T; 21 }
總體複雜度爲O(NlogN)。blog