程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> c++ 數據結構-一個程序,哈夫曼樹的構造遍歷打印,編碼解碼,缺少遍歷和打印

c++ 數據結構-一個程序,哈夫曼樹的構造遍歷打印,編碼解碼,缺少遍歷和打印

編輯:編程綜合問答
一個程序,哈夫曼樹的構造遍歷打印,編碼解碼,缺少遍歷和打印

#include
#include /* 數組頭文件 /
#include
#define MAX 999 /
定義長度 /
typedef struct{ /
定義哈夫曼編碼的結構數組 /
char data;
int weight; /
定義權值 /
int parent;
int lchild;
int rchild;
}huffmannode;
typedef struct{ /
定義保存哈夫曼結構體 /
char bits[50];
int start;
}huffmancode ;
void main()
{
huffmannode ht[100]; /
定義儲存權值的空間 /
huffmancode cd[100];
char string[100]; /
定義數組存儲空間 /
char hcd[100];
int i,j,x,y,s1,s2,m1,m2,n,c,f,k;
printf("please input the n ="); /
輸入字符的個數 /
scanf("%d",&n);
printf("\n============================\n");
for(i=0;i<n;i++)
{

getchar(); /
獲得輸入的字符 /
printf("please input the value :");
scanf("%c",&ht[i].data); /
輸入字符函數 /
printf("please input the weight:\n");
scanf("%d",&ht[i].weight);
}
printf("\n=============================\n");
for(i=0;i<2*n-1;i++)
{
ht[i].parent=ht[i].lchild=ht[i].rchild=-1; /
初始化父結點,左右子結點 /
}
for (i=n;i<2*n-1;i++)
{
s1=s2=0; /
初始化變量 /
m1=m2=MAX;
for (j=0;j<i;j++)
{
if (ht[j].weight<m1 &&ht[j].parent==-1) /
尋找無父結點的最小值 /
{
m2=m1;
s2=s1;
m1=ht[j].weight;
s1=j; /
尋找當前最小值 /
}
else if(ht[j].weight<m2 &&ht[j].parent==-1) /
尋找無父結點的次小值 /
{
m2=ht[j].weight;
s2=j;
} /
尋找次小值 /
}
ht[s1].parent=i; /
s1的父結點為i /
ht[s2].parent=i;
ht[i].weight=m1+m2; /
最小值的權值相加為i的權值 /
ht[i].lchild=s1; /
i的左子為s1 /
ht[i].rchild=s2; /
i的右子為s2 /
}
for(i=0;i<n;i++)
{
cd[i].start=n;
x=i;
y=ht[x].parent; /
記錄父結點 /
while (y!=-1)
{
if (ht[y].lchild==x)
cd[i].bits[cd[i].start]='0'; /
給字符賦0值 /
else
cd[i].bits[cd[i].start]='1'; /
給字符賦1值 /
cd[i].start--;
x=y;
y=ht[y].parent;
}
}
printf("\cout the huffmancode:\n");
for (i=0;i<n;i++)
{
printf("%c:",ht[i].data); /
輸出字符 /
for(j=cd[i].start;j<=n;j++){
printf("%c",cd[i].bits[j]); /
輸出字符的01代碼 /
}
printf("\n");
}
printf("\n=============================\n");
printf("\n Please input the message:\n");
scanf("%s",string); /
輸入字符串 /
for(i=0;string[i]!='0';i++)
{
for(c=0;c<=n;c++)
if(string[i]==ht[c].data) /
尋找與輸入字符相匹配的字母 /
{
for(j=cd[c].start;j<=n;j++)
printf("%c",cd[c].bits[j]); /
輸出字母代碼 /
break;
}
}
printf("\n=============================\n");
printf("Please input the HuffmanCode:\n");
scanf("%s",hcd); /
輸入0、1代碼 /
f=2*n-2;
for(i=0;hcd[i]!='\0';i++)
{
if(hcd[i]=='0') /
判斷輸入為0,尋找左子 /
f=ht[f].lchild;
else if(hcd[i]=='1')
f=ht[f].rchild; /
判斷輸入為1,尋找右子 /
if(f<n)
{
printf("%c",ht[f].data); /
輸出字符串 */
f=2*n-2;
}
}
printf("\n");
getch();

}

最佳回答:


步驟1.構造哈夫曼樹,
2.輸入字符個數
3.輸入字符
4.輸入權值
5.遍歷打印輸出樹
6.亂序輸入字符,輸出編碼
7.亂序輸入編碼,輸出對應字符

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved