我要对英语文章进行哈夫曼编码,我构造了哈夫曼树后还没想好怎么编码,就先用非递归前序遍历一次,结果程序运行到一半停止了,编译过程中也没有发现任何错误(除了我在树的节点结构体的变量中赋值时,编译给我做了警告,但我改正后运行时还是出现如图所示的错误,如果把图中的两个if语句体删去任意一个,则可以运行成功,但相当于所有的左子树或右子树都被忽略了)水平很菜,
#include<bits/stdc++.h>
using namespace std;
struct treenode{
char letter='\0',code[10];
int weight;
struct treenode *next=NULL,*lchild=NULL,*rchild=NULL,*parent=NULL;
};
typedef struct treenode tn;//树的节点
void sorted(tn *T)//按权值data从小到大排序
{
tn *p,*q;
int swap;
char ch;
for(p=T->next;p!=NULL;p=p->next)
for(q=p->next;q!=NULL;q=q->next)
if(p->weight>q->weight)
{
swap=p->weight;
p->weight=q->weight;
q->weight=swap;
ch=p->letter;
p->letter=q->letter;
q->letter=ch;
}
return;
}
void creatree(tn *T)//创建哈夫曼树的其它节点
{
tn *p,*q,*r,*init;
int swap;
p=T->next;
q=p->next;
while(q!=NULL)
{
r=(tn*)malloc(sizeof(tn));
r->lchild=p;
p->parent=r;
r->rchild=q;
q->parent=r;
r->weight=p->weight+q->weight;
for(init=q;init->next!=NULL&&init->next->weight<r->weight;init=init->next);
r->next=init->next;
init->next=r;
p->next=NULL;
p=q->next;
q->next=NULL;
q=p->next;
}
return;
}
void preorder(tn *T)//前序遍历给每个叶子节点赋予哈夫曼编码 (尚未完成,这就是我要问的问题,运行结果只显示一半,根节点的右子树不显示)
{
tn *p,stack[20];
int count=0;
stack[count]=*T;
while(count>=0)
{
*p=stack[count];
count-=1;
printf("%d\n",p->weight);
if(p->rchild!=NULL)
{
count+=1;
stack[count]=*((*p).rchild);
}
if(p->lchild!=NULL)
{
count+=1;
stack[count]=*((*p).lchild);
}
}
return;
}
int main()
{
tn *t,*node,*end,*p,*q,*r,stack[20];
int i,j,k,n=0,count=0;
char a[1000];
int b[256]={0};
scanf("%s",a);
for(i=0;a[i]!='\0';++i)//统计每个字母的频率(出现次数)
{
if(a[i]>='A'&&a[i]<='Z')
for(j=65;j<=90;++j)
if(a[i]==(char)(j))
{
b[j]+=1;
break;
}
if(a[i]>='a'&&a[i]<='z')
for(j=97;j<=122;++j)
if(a[i]==(char)(j))
{
b[j]+=1;
break;
}
}
for(i=0;i<=255;i++)
{
if(b[i]!=0)
printf("%c %d\t",i,b[i]);
}
printf("\n");
t=(tn*)malloc(sizeof(tn));//构造叶子节点链表头结点
end=t;
for(i=0;i<=255;++i)//构造所有叶子节点的链表,并将字母和相应的频率赋值给叶子节点
if(b[i]!=0)
{
node=(tn*)malloc(sizeof(tn));
node->letter=(char)(i);
node->weight=b[i];
end->next=node;
end=node;
}
for(p=t->next;p!=NULL;p=p->next)//打印每个字符出现的频率
printf("%c %d\n",p->letter,p->weight);
printf("\n");
sorted(t);
for(p=t->next;p!=NULL;p=p->next)//从小到大打印每个字符出现的频率
printf("%c %d\n",p->letter,p->weight);
creatree(t);
for(t=t->next;t->parent!=NULL;t=t->parent);//使指针t指向哈夫曼树的头结点
preorder(t);
return 0;
}
```望指点