| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 533 人关注过本帖
标题:huffman树,不知错哪了!
只看楼主 加入收藏
shyh69
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2006-10-13
收藏
 问题点数:0 回复次数:0 
huffman树,不知错哪了!
# include<stdio.h>
# include<stdlib.h>
struct node
{int m;
struct node* lchild;
struct node* rchild;
};
struct node* init(int w[],int n) /*建立数组存放原始的n棵树,初始化,从大到小排*/
{int i,j,t;
struct node* tree;
tree=(struct node*)malloc((n+1)*sizeof(struct node));
for(i=0;i<n;i++)
{tree[i].m=w[i];
tree[i].lchild=NULL;
tree[i].rchild=NULL;
}
for(i=0;i<n-1;i++)
{for(j=i+1;j<n;j++)
if(tree[i].m<tree[j].m)
{t=tree[i].m;
tree[i].m=tree[j].m;
tree[j].m=t;
}}
return(tree);
}
struct node* huffman(int w[],int n)  /*不断合并权值最小的两棵树,插入原数组,最后只剩一棵数时返回*/
{int i,j;
struct node* r;
struct node* tree;
tree=init(w,n);
while(n>1)
{i=0;
r=(struct node*)malloc(sizeof(struct node));
r->lchild=(tree+n-1);
r->rchild=(tree+n-2);
r->m=(tree+n-1)->m+(tree+n-2)->m;
j=n-2;
while((((tree+i)->m)>(r->m))&&(i<(n-2))) i++;
while(j>i) {*(tree+j)=*(tree+j-1);j--;}
*(tree+j)=*r;
n--;
}
return(tree);
}
printtree(struct node* T) /*先序遍历树*/
{if(T)
{printf("%d ",T->m);
printtree(T->lchild);
printtree(T->rchild);
}
}
main()
{int w[3]={1,5,2}; /*权值*/
struct node* head=NULL;
head=huffman(w,3);
printtree(head);
getch();
}
搜索更多相关主题的帖子: huffman 知错 
2006-11-28 00:32
快速回复:huffman树,不知错哪了!
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019771 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved