该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
/*
** Copyright (C) QPSOFT.COM All rights reserved.
*/
#include
#include
//#define MaxNode 20
struct HtNode
{
double weight;
int parent,lchild,rchild;
};
struct HtTree
{
struct HtNode *ht;
int root;
};
typedef struct HtTree *PHtTree;
PHtTree Huffman(int n,int w[])
{
PHtTree pht;
int i,j,p1,p2;
double min1,min2;
if(n<1)
return NULL;
pht=(PHtTree)malloc(sizeof(struct HtTree));
pht->ht=(struct HtNode*)malloc(sizeof(struct HtNode)*(2*n-1));
for(i=0;i<2*n-1;i++)
{
pht->ht[i].parent=0;
if(i
pht->ht[i].weight=w[i];
else
pht->ht[i].parent=-1;
}
for(i=0;i
{
p1=p2=0;
min1=min2=w[0];
for(j=0;j
{
if(pht->ht[j].parent==0)
{
if(pht->ht[j].weight
{
min2=min1;
min1=pht->ht[j].weight;
p2=p1;
p1=j;
}
else if(pht->ht[j].weight
{
min2=pht->ht[j].weight;
p2=j;
}
}
}
pht->ht[p1].parent=n+i;
pht->ht[p2].parent=n+i;
pht->ht[n+i].lchild=p1;
pht->ht[n+i].rchild=p2;
}
return pht;
}
void PreOrderTravelse(HtTree T)//
{
HtTree T1,T2;
T1=T2=T;
int i=T.root;/
T1.root=T.ht[i].lchild;
T2.root=T.ht[i].rchild;
printf("%d",T.ht[i].weight);
PreOrderTravelse(T1);//
PreOrderTravelse(T2);/
}
int main()
{
HtTree T;
PHtTree PT;
int w[5]={1,2,3,4,5};
PT=Huffman(5,w);
T=*PT;
PreOrderTravelse(T);
return 0;
}