資料結構---哈夫曼樹(詳解)
阿新 • • 發佈:2018-12-30
main.cpp
- #include”HuffmanTree.h”
- int main()
- {
- HuffmanTree HT;
- int *w,i,n;
- unsigned int sum = 0;
- printf(”請輸入測試的個數(>1): ”);
- scanf(”%d”,&n);
- w=(int *)malloc((n+1)*sizeof(int *));
- w[0]=0;
- printf(”Enter weight:\n”);
- for(i=1;i<=n;i++)
- {
- printf(”w[%d]= ”
- scanf(” %d”,&w[i]);
- }
- sum= HuffmanCoding(HT,w,n);
- printf(”%d\n”,sum);
- system(”pause”);
- return 0;
- }
HuffmanTree.cpp
- #include”HuffmanTree.h”
- unsigned int HuffmanCoding(HuffmanTree &HT,int *w,int n)
- {
- unsigned int i,s1=0,s2=0,m;
- unsigned int
- HuffmanTree p;
- MinCode min;
- if(n<=1) //輸入個數少於1,則返回
- return 0;
- m=2*n-1; //總結點數
- HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode)); //申請的哈夫曼樹的所佔空間
- for(p=HT,i=0;i<=n;i++,p++,w++) //將n個結點 賦值權重,並初始化兒子結點
- {
- p->weight=*w;
- p->parent=0;
- p->lchild=0;
- p->rchild=0;
- }
- for(;i<m;i++,p++) //將剩餘的結點初始化兒子結點
- {
- p->weight=0;
- p->parent=0;
- p->lchild=0;
- p->rchild=0;
- }
- for(i=n+1;i<=m;i++) //對剩餘結點,結合權重,進行建立哈夫曼樹
- {
- min=Select(HT,i-1);//在前n個結點中挑選2個權重最小的結點。
- s1=min.s1;
- s2=min.s2;
- HT[s1].parent=i;
- HT[s2].parent=i;
- HT[i].lchild=s1;
- HT[i].rchild=s2;
- HT[i].weight=HT[s1].weight+HT[s2].weight;//此時 父節點的權重為。
- sum +=HT[i].weight;
- }
- return sum;
- }
- MinCode Select(HuffmanTree &HT,unsigned int n)
- {
- unsigned int min,smin,temp=0,i;
- int s1,s2,temp2;
- MinCode node;
- for(i=1;i<=n;i++)//挑選出一個 父節點 為零的結點
- {
- if(HT[i].parent==0)
- {
- min=HT[i].weight;
- s1=i;
- break;
- }
- }
- temp=i++;
- for(;i<=n;i++) //挑選出的 s1與 其他的父節點為零的結點進行比較
- if ((HT[i].weight<min)&&HT[i].parent==0)
- {
- min=HT[i].weight;
- s1=i;
- }
- for(i=temp;i<=n;i++)//接著 挑選s2
- {
- if(HT[i].parent == 0 && i != s1)
- {
- smin=HT[i].weight;
- s2=i;
- break;
- }
- }
- for(i=1;i<=n;i++) //並與其他結點進行比較
- {
- if(HT[i].weight<smin&&i != s1&&HT[i].parent==0)
- {
- smin=HT[i].weight;
- s2=i;
- }
- }
- if(s1>s2){
- temp=s1;
- s1=s2;
- s2=temp;
- }
- node.s1=s1;
- node.s2=s2;
- return node;
- }
DS.h
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <math.h>
- #define TRUE 1
- #define FALSE 0
- #define OK 1
- #define ERROR 0
- typedefint Status;
HuffmanTree.h
- #include”DS.h”
- typedefstruct
- {
- unsigned int weight;
- unsigned int parent, lchild, rchild;
- } HTNode, *HuffmanTree; //動態分配陣列儲存哈夫曼樹
- typedefstruct{
- unsigned int s1;
- unsigned int s2;
- }MinCode;
- typedefchar * * HuffmanCode; //動態分配陣列儲存哈夫曼編碼表
- unsigned int HuffmanCoding(HuffmanTree &HT,int *w,int n);
- //void Select(HuffmanTree HT,unsigned int n,int s1,int s2);
- MinCode Select(HuffmanTree &HT,unsigned int n);