數據結構-樹-定義,哈夫曼

//樹和二叉樹
//孩子鏈表表示法
const int MAXND=20;
typedef struct bnode
{
	int child;
	struct bnode *next;
}node,*childlink;
typedef struct
{
	DataType data;
	//方便找雙親可以加int parent;
	childlink hp;
}headnode;
headnode link[MAXND];


//孩子兄弟鏈表表示法
typedef struct tnode
{
	DataType data;
	struct tnode *son,*brother;
} *Tree;

//雙親表示法
const int size=10;
typedef struct
{
	DataType data;
	int parent;
}Node;
Node slist[size];


//哈夫曼樹
//定義:二叉樹順序存儲,四個域組成
const int n=10;
typedef struct
{
	float w;
	int parent,lchild,rchild;
}node;
typedef node hftree [2*n-1];
//算法
void Huffman (int k,float w[],hftree T)
{
	int i,j,x,y;
	float m,n;
	for (i=0;i<2*k-1;i++)
	{
		T[i].parent=-1;
		T[i].lchild=-1;
		T[i].rchild=-1;
		if (i<k)
			T[i].w=w[i];
		else
			T[i].w=0;
	}
	for (i=0;i<k-1;i++)
	{
		x=0;
		y=0;
		m=MAX;
		n=MAX;
		for (j=0;j<k+i;j++)
			if((T[j].w<m)&&(T[j].parent==-1))
			{
				n=m;
				y=x;
				m=T[j].w;
				x=j;
			}
			else if ((T[j].w<n)&&(T[j].parent==-1))
			{
				n=T[j].w;
				y=j;
			}
		T[x].parent=k+i;T[y].parent=k+i;
		T[k+i].w=m+n;
		T[k+i].lchild=x;
		T[k+i].rchild=y;
	}
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章