输入一个 数n 代表叶节点数目
输入n个叶节点的权重
cnt建树,中序遍历输出每个叶节点的权重和哈夫曼码
#include <iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct node
{
int w;
string ma;
int lc;
int rc;
node()
{
ma.clear();
lc=-1;
rc=-1;
}
node(int x,int l,int r)
{
w=x;
lc=l;
rc=r;
}
bool operator <(const node& d)const
{return w>d.w;}
bool operator >(const node& d)const
{return w<d.w;}
};
priority_queue<node> que;
int sum;
int cnt;
node a[200];
void dfs(int root,string t)
{ if(root==-1)
return ;
a[root].ma+=t;
dfs(a[root].lc,t+"0");
dfs(a[root].rc,t+"1");
}
void inorder(int root)
{
if(root==-1)
return ;
inorder(a[root].lc);
if(a[root].lc==-1&&a[root].rc==-1)
{
cout<<a[root].w<<' '<<a[root].ma<<endl;
sum++;
}
inorder(a[root].rc);
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
que.push(node(x,-1,-1));
}
while(que.size()>1)
{
node x,y;
x=que.top();
que.pop();
a[cnt++]=x;
y=que.top();
que.pop();
a[cnt++]=y;
que.push(node(x.w+y.w,cnt-2,cnt-1));
}
a[cnt]=que.top();
int root=cnt;
string t;
t.clear();
dfs(root,t);
inorder(root);
/* cout<<endl;
cout<<sum<<endl;*/
return 0;
}