可能編譯時會有些語法小錯誤(比如分號,->,等),很容易就自己糾正了哦,思路絕對是完全正確的,所以用的話就自己試著改改吧,直接復制粘貼,就正確,豈不是太沒寫代碼體驗了,自己改改才印象更加深刻的呢(▽)~~~~;
//構造哈夫曼樹
#include<iostream>
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 CreateHuffmanTree(HuffmanTree &HT,int n){
im,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<<"please input the weight of leaf child:\n";
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].rchild=i;
HT[i].lchild=s1;
HT[i].rchild=s2;
HT[i].weight=HT[s1].weight+HT[s2].weight;
}
}
void main(){
HuffmanTree HT;
int n;
cout<<"please input the num of leaf child:\n";
cin>>n;
CreateHuffmanTree(HT,n);
cout<<"finish!\n";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/124285.html
標籤:其他
上一篇:帶頭結點的中序線索化
下一篇:遍歷線索二叉樹
