赫夫曼树中的挑选最小和次小数时出现意外的错误(求高手)
void select(int *weight_s,int *weight_ss,int j,huffantree treenode[])//选择2个权重较小的结点,把它们在数组中的序号用指针参数返回
{
int i=1;
while(treenode[i].parent!=-1||treenode[i].weight<treenode[*weight_s].weight)
//找到第一个父母结点没有处理的结点序号
{
i++;
}
*weight_s=i;
*weight_ss=i;
i++;
for(;i<j;i++)
{
if(treenode[i].parent=-1)
{
if(treenode[i].weight<treenode[*weight_ss].weight)
{
*weight_s=*weight_ss;
*weight_ss=i;
}
else
{
if(treenode[i].weight<treenode[*weight_s].weight)
{
*weight_s=i;
}
}
}
}
}
void build_tree(int *weight_s,int *weight_ss,int tree_num,huffantree treenode[])
//构建最优二叉树
{
int i;
int j=N+1;
for(i=0;i<N-1;i++,j++)
{
select(weight_s,weight_ss,j,treenode);
treenode[*weight_s].parent=j;
treenode[*weight_ss].parent=j;
treenode[j].lchild=*weight_s;
treenode[j].rchild=*weight_ss;
treenode[j].weight=treenode[*weight_s].weight+treenode[*weight_ss].weight;
}
}
int main()
{
int i;
huffancode hc;
int g=0;
int h=0;
//由于后面的weight_s和weight_ss指向的内存可能是非法的,所以调试的时候编译器可
//能会报告一个内存访问错误。
//这里g和h是为了让后面的weight_s和weight_ss指向合法的内存,避免可能发生的错误
int tree_num;
//树结点个数
int *weight_s=&g,*weight_ss=&h;
//weight_s,weight_ss分别指向权重第二小和最小的结点序号的位置
huffantree *treenode;
tree_num=2*N-1;
treenode=(huffantree *)malloc((tree_num+1)*sizeof(huffantree));
printf("请输入各个字符的名称极其权重:\n");
for(i=1;i<=N;i++)
{
printf("第%d个字符:\n",i);
treenode[i].name=getchar();
scanf("%d",&treenode[i].weight);
fflush(stdin);
treenode[i].lchild=-1;
treenode[i].rchild=-1;
treenode[i].parent=-1;
}
build_tree(weight_s,weight_ss,tree_num,treenode);
code_tree(treenode,hc);
for(i=0;i<N;i++)
{
printf("%s",hc[i]);
putchar('\n');
}
read_code(treenode,hc);
return 0;
}
这时要赫夫曼编码的一部分代码 每次挑选2个最小和最小的树
我输入的结点依次是 a(5) b(19) c(1) d(8) e(13) 括号里面代表字符的权重
然后第一次得到的最小和次小的正确了 之后 再进行第二次挑选时上次次小的那个字符的父母结点变成了-1(所有刚开始出事化都是-1) 而不是6 这是为什么呢?
treenode[*weight_s].parent=j;
这句明明已经处理了