哈夫曼树

<pre name="code" class="cpp">这棵哈夫曼树只能计算根结点的权值
//哈夫曼树
#include<stdio.h>
#include<stdlib.h>
typedef int Elemtype;
#define MIN -10000
typedef struct TreeNode{
    int Weight;
    struct TreeNode *left,*right;
}*HuffmanTree;
typedef struct HeadStruct{
    Elemtype *data;
    int Size;
    int Capacity;
}*MinHeap;
MinHeap Creat(int max)
{
    MinHeap H;
    H=(struct HeadStruct *)malloc(sizeof(struct HeadStruct));
    H->data=(Elemtype *)malloc((max+1)*sizeof(Elemtype));
    H->Size=0;
    H->Capacity=max;
    H->data[0]=MIN;
    return H;
}
int isFull(MinHeap H)
{
    return H->Size==H->Capacity;
}
int isEmpty(MinHeap H)
{
    return H->Size==0;
}
void Insert(HuffmanTree T,MinHeap H)
{
    if(H->Size==H->Capacity)
    {
        printf("This heap is full\n");
        return ;
    }
    int i=++H->Size;
    while(H->data[i/2]>T->Weight)
    {
        H->data[i]=H->data[i/2];
        i/=2;
    }
    H->data[i]=T->Weight;
}
HuffmanTree DeleteMin(MinHeap H)
{
    HuffmanTree Haff;
    int parent,child;
    Elemtype temp;
    if(isEmpty(H))
    {
        printf("This heap is empty\n");
        return NULL;
    }
    Haff=(struct TreeNode *)malloc(sizeof(struct TreeNode));
    Haff->Weight=H->data[1];
    temp=H->data[H->Size--];
    for(parent=1;parent*2<=H->Size;parent=child)
    {
        child=parent*2;
        if(parent!=H->Size&&(H->data[child]>H->data[child+1])) child++;
        if(temp<H->data[child]) break;
        else H->data[parent]=H->data[child];
    }
    H->data[parent]=temp;
    return Haff;
}
void swap(int i,int max,MinHeap H)
{
    Elemtype t=H->data[max];
    H->data[max]=H->data[i];
    H->data[i]=t;
}
void HeapAdjust(MinHeap H,int i)
{
    int lchild=i*2;
    int rchild=i*2+1;
    int min=i;
    if(i<=H->Size/2)
    {
        if(lchild<=H->Size&&H->data[lchild]<H->data[min])
            min=lchild;
        if(rchild<=H->Size&&H->data[rchild]<H->data[min])
            min=rchild;
        if(min!=i)
        {
            swap(i,min,H);
            HeapAdjust(H,min);
        }
    }
}
HuffmanTree Huffman(MinHeap H)
{
    HuffmanTree T;
    int round=H->Size;
    for(int i=H->Size/2;i>=1;i--)
        HeapAdjust(H,i);
    for(int i=1;i<round;i++)
    {
        T=(struct TreeNode *)malloc(sizeof(struct TreeNode));
        T->left=DeleteMin(H);
        T->right=DeleteMin(H);
        T->Weight=T->left->Weight+T->right->Weight;
        Insert(T, H);
    }
    T=DeleteMin(H);
    return T;
}
int main()
{
    MinHeap H;
    HuffmanTree T;
    int max;
    scanf("%d",&max);
    H=Creat(max);
    int cnt=1;
    while(scanf("%d",&H->data[cnt])&&H->data[cnt]){cnt++;H->Size++;}
    T=Huffman(H);
    return 0;
}


 
 

你可能感兴趣的:(哈夫曼树)