哈夫曼树的构造

来源:互联网 发布:亮剑online知乎 编辑:程序博客网 时间:2024/06/02 18:23

哈夫曼树的特点:n个结点全为叶子结点,并且总共有2*n-1个结点,权值路径之和最小。

#include <stdio.h>#include <stdlib.h>#define max 100struct huffmantree{    int weight;    struct huffmantree *lchild;    struct huffmantree *rchild;    struct huffmantree *next;};//函数声明void addNode(struct huffmantree *, struct huffmantree *);struct huffmantree* createHfmtree(int *, int);int getWpl(struct huffmantree *, int);void InOrder(struct huffmantree *);int main(){    int w[max];    int i, n, wpl;    struct huffmantree *ht;    while(1)    {        printf("输入节点个数n=");        scanf("%d", &n);        printf("输入%d个结点的权值:",n);        for(i = 0; i < n; i ++)        {            scanf("%d", &w[i]);        }        ht = createHfmtree(w, n);        wpl = getWpl(ht, 0);        printf("构造的哈夫曼树的权值路径之和:%d\n", wpl);        printf("前序遍历哈夫曼树:");        InOrder(ht);        printf("\n");    }    return 0;}struct huffmantree* createHfmtree(int *w, int n){    int i;    struct huffmantree *head, *pl, *pr, *proot;    head = (struct huffmantree *)malloc(sizeof(struct huffmantree));    head->next = NULL;    //建立一个有序结点关键字由小到大的链表    for(i = 0; i < n; i ++)    {        struct huffmantree *pnode =(struct huffmantree *)malloc(sizeof(struct huffmantree));        pnode->weight = *(w + i);        pnode->lchild = pnode->rchild = pnode->next = NULL;        addNode(head, pnode);    }    //从链表头开始顺序取两个结点构造哈夫曼树    while(head->next)    {        //将头指针移指到第三个结点        if(head->next->next == NULL)            break;        pl = head->next;        pr = pl->next;        head->next = pr->next;        //将取到的前两个结点构造哈夫曼树        proot = (struct huffmantree *)malloc(sizeof(struct huffmantree));        proot->weight = pl->weight + pr->weight;        proot->lchild = pl;        proot->rchild = pr;        //将构造的新结点重新插入到有序链表中        addNode(head, proot);    }    return head->next;//返回头指针的next极为哈夫曼树的根节点指针}//添加结点到有序的链表中void addNode(struct huffmantree *head, struct huffmantree *pnode){    struct huffmantree *t = head;    while(t->next && t->next->weight < pnode->weight)        t = t->next;    pnode->next = t->next;    t->next = pnode;}//计算权值路径之和int getWpl(struct huffmantree *ht, int level){    if(ht == NULL)        return 0;    if(!ht->lchild && !ht->rchild)    {        return ht->weight * level;    }    return getWpl(ht->lchild, level + 1) + getWpl(ht->rchild, level + 1);}//前序遍历哈夫曼树void InOrder(struct huffmantree *ht){    if(ht)    {        printf("%d ",ht->weight);        InOrder(ht->lchild);        InOrder(ht->rchild);    }}

输出的结果:

构造的哈夫曼树的形式如下:

              15

           /         \

         6             9

      /      \         /     \

     3      3      4      5

   /    \

 1      2

权值路径之和为1*3+2*3+3*2+4*2+5*2=33

很显然前序遍历的结果为15 6 3 1 2 3 9 4 5

原创粉丝点击