#include <stdio.h>#include<iostream>using namespacestd;structHuffnode//Huffman tree node structure{ intWeight//Weighted Value intParent//parent Node intLchild;//left son intRchild;//Right son};structHuffcode//Huffman tree node coding structure{ intbit[Ten];//Store Huffman Code intStart//The starting position of Huffman encoding in the array intWeight//Weighted Value};//Implement Huffman codingvoidHuffman (intW[],intn,huffnode Hn[],huffcode hc[]) { intm1,m2; intx1,x2; Huffcode cd; intchild,parent; inti,j; for(i=0; i<2*n-1; i++)//Initialize Huffman tree { if(i<N) hn[i].weight=W[i]; ElseHn[i].weight=0; Hn[i].parent=0; Hn[i].lchild= -1; Hn[i].rchild= -1; } for(i=0; i<n-1; i++)//Constructing the N-1 branch node of Huffman Tree{M1= m2 = +; X1= x2 =0; for(j=0; j<n+i; J + +) { if(hn[j].weight<m1&&hn[j].parent==0) {m2=M1; M1=Hn[j].weight; X2=X1; X1=J; } Else if(hn[j].weight<m2&&hn[j].parent==0) {m2=Hn[j].weight; X2=J; }} hn[n+i].weight = hn[x1].weight+Hn[x2].weight; Hn[x1].parent= n+i; Hn[x2].parent= n+i; Hn[n+i].lchild =X1; Hn[n+i].rchild =x2; } for(i=0; i<n; i++)//Huffman code generated by Huffman tree{cd.weight=Hn[i].weight; Cd.start= N1; Child=i; Parent=hn[i].parent; while(parent!=0) { if(hn[parent].lchild==Child ) Cd.bit[cd.start]=0; Else if(hn[parent].rchild==Child ) Cd.bit[cd.start]=1; Cd.start--; Child=parent; Parent=hn[child].parent; } hc[i].weight=Cd.weight; Hc[i].start=Cd.start; for(j=hc[i].start+1; j<n; J + +) Hc[i].bit[j]=Cd.bit[j]; }}intMainintargcChar*argv[]) { intW[] = {4,2,6,8,3,2,1}; intn =7; Huffnode*hn =Newhuffnode[2*n-1]; Huffcode*HC =NewHuffcode[n]; Huffman (W,N,HN,HC); cout<<"Huffman code is as follows:"<<Endl; for(intI=0; i<n; i++) {cout<<"weight="<" "<<"code="; for(intj=hc[i].start+1; j<n; J + +) cout<<Hc[i].bit[j]; cout<<Endl; } return 0;}
Huffman number and Huffman coding