关于数据结构:构建赫夫曼树及求赫夫曼编码从叶子到根逆向

38次阅读

共计 1395 个字符,预计需要花费 4 分钟才能阅读完成。

#include<iostream>
#include<string.h>
using namespace std;
typedef struct{
    int weight;
    int parent,lchild,rchild;
}HTNode,*HuffmanTree;
void Select(HuffmanTree HT,int len,int &s1,int &s2){
    int i,min1=0x3f3f3f3f,min2=0x3f3f3f3f;
    for(i=1;i<=len;i++){if(HT[i].weight<min1&&HT[i].parent==0){min1=HT[i].weight;
            s1=i;
        }    
    }
    int temp=HT[s1].weight;
    HT[s1].weight=0x3f3f3f3f;
    for(i=1;i<=len;i++){if(HT[i].weight<min2&&HT[i].parent==0){min2=HT[i].weight;
            s2=i;
        }
    }
    HT[s1].weight=temp;
}
// 结构赫夫曼树
void CreatHuffmanTree(HuffmanTree &HT,int n){
    int m,s1,s2,i;
    if(n<=1) return;
    m=2*n-1;
    HT=new HTNode[m+1];      
    for(i=1;i<=m;++i){HT[i].parent=0;  
        HT[i].lchild=0;  
        HT[i].rchild=0; 
    }
    cout<<"叶子结点权值:";
    for(i=1;i<=n;++i)         
        cin>>HT[i].weight;  
    for(i=n+1;i<=m;++i){Select(HT,i-1,s1,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;     
    }                                                
 }    
 typedef char **HuffmanCode;
 // 赫夫曼编码 
 void CreatHuffmanCode(HuffmanTree HT,HuffmanCode &HC,int n){
    int i,start,c,f;
    HC=new char*[n+1];                                 
    char *cd=new char[n];                            
    cd[n-1]='\0';                                    
    for(i=1;i<=n;++i){                                                  
        start=n-1;                                  
        c=i; 
        f=HT[i].parent;                             
        while(f!=0){                                          
            --start;                              
            if(HT[f].lchild==c)  
                cd[start]='0';                        
            else 
                cd[start]='1';                     
            c=f; 
            f=HT[f].parent;                     
        }                                                 
        HC[i]=new char[n-start];                     
        strcpy(HC[i], &cd[start]);                   
    }
    delete cd;                                        
}                                                    
void show(HuffmanTree HT,HuffmanCode HC,int n){for(int i=1;i<=n;i++)
        cout<<HT[i].weight<<"赫夫曼编码为:"<<HC[i]<<endl;
}                                                
int main(){
    HuffmanTree HT;
    int n;
    cout<<"叶子结点个数:";
    cin>>n;
    CreatHuffmanTree(HT,n);
    HuffmanCode HC;
    CreatHuffmanCode(HT,HC,n);
    show(HT,HC,n);
}

正文完
 0