求大神看看我的破代码,哈夫曼树问题
构建和哈夫曼树,并且遍历哈夫曼树。。
不报错,但是遍历不出来是怎么回事。。。
#include<iostream.h>
#include<stdlib.h>
#include<stdio.h>
typedef struct{
int weight;
int parent,lchild,rchild;
}HNode,*HuffmanTree;
HuffmanTree creat(HuffmanTree ht,int n);
void PutInScreen(HuffmanTree ht,int n);//遍历哈夫曼树
int main()
{
int n;
HuffmanTree ht;
ht=creat(ht,n);
PutInScreen(ht,n);
return 0;
}
HuffmanTree creat(HuffmanTree ht,int n)
{ int *select(HuffmanTree ht,int n);
int m,i;
int *a;
cout<<"开始构建哈夫曼树"<<endl;
cout<<"请输入哈夫曼树的叶子节点个数:"<<endl;
cin>>n;
m=2*n-1;
ht=(HuffmanTree)malloc(sizeof(HNode)*(m+1));
for(i=1;i<=m+1;i++)
{
ht[i].parent=0;
ht[i].lchild=0;
ht[i].rchild=0;
}
cout<<"请输入每个叶子节点的权值:"<<endl;
for(i=1;i<=n;i++)
cin>>ht[i].weight;
for(i=n+1;i<=m;i++)
{ a=select(ht,i-1);//在里面(1~n-1)选择两个其双亲域为0且权值最小的结点,并返回它们在HT中的序号s1和s2;
//删除
ht[i].lchild=(*a);
ht[i].rchild=*(a+1);
ht[*a].parent=i;
ht[*(a+1)].parent=i;
ht[i].weight=ht[*a].weight+ht[*(a+1)].weight;
}
return ht;
}
int *select(HuffmanTree ht,int n)
{
int i,j;
int *a;
a=(int *)malloc(sizeof(int)*2);//
for(i=1;i<=n;i++)
{
if(ht[i].parent!=0) continue;
if(ht[i].weight>ht[i+1].weight) (*a)=i;
else (*a)=i+1;
}
for(i=1;i<=n;i++)
{
if(ht[i].parent!=0) continue;
if(ht[i].weight>ht[i+1].weight&&*(a+1)!=(*a)) *(a+1)=i;
else *(a+1)=i+1;
}
return a;
}
void PutInScreen(HuffmanTree ht,int n)
{
int i;
for(i=1;i<=2*n-1;i++)
{
cout<<"结点序号"<<i;
cout<<"权重 "<<ht[i].weight<<" "<<"双亲 "<<ht[i].parent;
cout<<"左孩子 "<<ht[i].lchild<<" "<<"右孩子 "<<ht[i].rchild;
}
}