不具体介绍了,只给出我的代码和结果,可能代码有些部分不是很规范,有空再修改下。改了能有4个小时。。好开心,哈哈哈
#include<iostream>
#include<string>
using namespace std;
int maxsize=100;
struct huffmannode {
int weight;
char a;
huffmannode* leftchild;
huffmannode* rightchild;
huffmannode(){}
huffmannode(huffmannode* aa, huffmannode* bb, int num, char el):leftchild(aa), rightchild(bb), weight(num), a(el) {
}
};
struct input{
int weight;
char a;
};
void bubblesort(huffmannode *aa, int begin, int asize) { //按照权值从小到大排序
for(int i=begin;i<asize;i++) {
for(int j=begin;j<asize-i-1+begin;j++) {
if(aa[j].weight>aa[j+1].weight) {
huffmannode c;
c=aa[j];
aa[j]=aa[j+1];
aa[j+1]=c;
}
}
}
}
huffmannode* createhuffmantree(input *aa, int asize) {
huffmannode* huffmantree=new huffmannode[maxsize];
//huffmannode* huffmantree[100];
if(asize==0) return nullptr;//空树
else if(asize==1) {//只有一个节点
huffmannode* res;
res->a=aa[0].a;
res->weight=aa[0].weight;
res->leftchild=nullptr;
res->rightchild=nullptr;
return res;
}
else {//树有多个节点
for(int i=0;i<asize;i++) {
huffmannode *re=new huffmannode(nullptr, nullptr, aa[i].weight, aa[i].a);
huffmantree[i].a=re->a;
huffmantree[i].weight=re->weight;
huffmantree[i].leftchild=nullptr;
huffmantree[i].rightchild=nullptr;
}
for(int i=0;i<asize-1;) {
bubblesort(huffmantree, i, asize);
huffmannode *re=new huffmannode(&huffmantree[i], &huffmantree[i+1], (huffmantree[i].weight+huffmantree[i+1].weight), '0');
asize++;
huffmantree[asize-1]=*re;
i=i+2;
}
}
return &huffmantree[asize-1];
}
void print(huffmannode* res) {
if(res==nullptr) return ;
if(res!=nullptr) {
cout<<"当前结点:"<<res->weight<<" "<<res->a<<".";
if(res->leftchild)
cout<<"它的左孩子:"<<res->leftchild->weight<<" "<<res->leftchild->a<<".";
else
cout<<"无左孩子.";
if(res->rightchild)
cout<<"它的右孩子:"<<res->rightchild->weight<<" "<<res->rightchild->a<<".";
else
cout<<"无右孩子.";
cout<<endl;
print(res->leftchild);
print(res->rightchild);
}
return ;
}
int main() {
int n;
cout<<"输入节点个数:";
cin>>n;
input *aa=new input[n];
for(int i=0;i<n;i++) {
cout<<"输入第"<<i+1<<"个字母:";
cin>>aa[i].a;
cout<<"输入第"<<i+1<<"个字母的权值:";
cin>>aa[i].weight;
}
huffmannode* res=createhuffmantree(aa, n);
print(res);
delete []aa;
system("pause");
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/c7933ad6d1f3c096951299661247f0e5.png)