数据结构&&哈弗曼树和哈弗曼编码

1.什么是哈夫曼树和哈弗曼编码

大家来看这样一道面试题(题目来自于<程序员面试宝典>)。用二进制来编码字符串”abcdabaa”,需要能够根据编码,解码回原来的字符串,最少需要多长的二进制字符串?

A.12 B.14 C.18 D.24

解析:典型的哈弗曼编码问题:字符串”abcdabaa”有4个a、2个b、1个c、1个d。构造哈弗曼树如下图所示(图好丑《数据结构&&哈弗曼树和哈弗曼编码》)。a编码0(1位),b编码10(2位),d编码111(3位)。二进制字符串的总长度为1*4+2*2+3*1+3*1。

《数据结构&&哈弗曼树和哈弗曼编码》

接下来让我们一同回顾哈弗曼树的理论知识吧。在一般的数据结构的书中,树的那章后面,著者一般都会介绍一下哈夫曼(HUFFMAN)树和哈夫曼编码。哈夫曼编码是哈夫曼树的一个应用。哈夫曼编码应用广泛,如JPEG中就应用了哈夫曼编码。 首先介绍什么是哈夫曼树。哈夫曼树又称最优二叉树,是一种带权路径长度最短的二叉树。所谓树的带权路径长度,就是树中所有的叶结点的权值乘上其到根结点的 路径长度(若根结点为0层,叶结点到根结点的路径长度为叶结点的层数)。树的带权路径长度记为WPL= (W1*L1+W2*L2+W3*L3+…+Wn*Ln),N个权值Wi(i=1,2,…n)构成一棵有N个叶结点的二叉树,相应的叶结点的路径长度为Li(i=1,2,…n)。可以证明哈夫曼树的WPL是最小的。名字解释:

(1)路劲(Path):从树中的一个结点到另一个结点之间的分支构成两个结点间的路径。
(2)路径长度(Path Length):路径上的分支树。
(3)树的路径长度(Path Length of Tree):从树的根结点到每个结点的路径长度之和。在结点数目相同的二叉树中,完全二叉树的路径长度最短。
(4)结点的权(Weight of  Node):在一些应用中,赋予树中结点的一个有实际意义的树。
(5)结点的带权路径长度(Weight Path Length of Node):从该结点到树的根结点的路径长度与该结点的权的乘积。
(6)树的带权路径长度(WPL):树中所有叶子结点的带权路径长度之和,记为           

《数据结构&&哈弗曼树和哈弗曼编码》

在下图所示的2棵二叉树,都有4个叶子结点,其权值分别1、2、3、4,他们的带权路径长度分别为:


(a)WPL = 1 x 2 + 2 x 2 + 3 x 2 + 4 X 2 = 20
(b)WPL = 1 x 1 + 2 x 2 + 3 x 3 + 4 x 3 = 28
(c)WPL  = 1 x 3 + 2 x 3 + 3 x 2 + 4 x 1 = 19

《数据结构&&哈弗曼树和哈弗曼编码》《数据结构&&哈弗曼树和哈弗曼编码》

其中,(c)图所示的二叉树的带权路径长度最小,这棵树就是哈夫曼树

2.哈夫曼树和编码步骤:

一、对给定的n个权值{W1,W2,W3,…,Wi,…,Wn}构成n棵二叉树的初始集合F= {T1,T2,T3,…,Ti,…,Tn},其中每棵二叉树Ti中只有一个权值为Wi的根结点,它的左右子树均为空。(为方便在计算机上实现算 法,一般还要求以Ti的权值Wi的升序排列。)
二、在F中选取两棵根结点权值最小的树作为新构造的二叉树的左右子树,新二叉树的根结点的权值为其左右子树的根结点的权值之和。
三、从F中删除这两棵树,并把这棵新的二叉树同样以升序排列加入到集合F中。
四、重复二和三两步,直到集合F中只有一棵二叉树为止。

简易的理解就是,假如我有A,B,C,D,E五个字符,出现的频率(即权值)分别为5,4,3,2,1,那么我们第一步先取两个最小权值作为左右子树构造一个新树,即取1,2构成新树,其结点为1+2=3,如图:

《数据结构&&哈弗曼树和哈弗曼编码》

虚线为新生成的结点,第二步再把新生成的权值为3的结点放到剩下的集合中,所以集合变成{5,4,3,3},再根据第二步,取最小的两个权值构成新树,如图:

《数据结构&&哈弗曼树和哈弗曼编码》

再依次建立哈夫曼树,如下图:

《数据结构&&哈弗曼树和哈弗曼编码》

其中各个权值替换对应的字符即为下图:

《数据结构&&哈弗曼树和哈弗曼编码》

所以各字符对应的编码为:A->11,B->10,C->00,D->011,E->010

哈弗曼编码是一种无前缀编码。解码时不会混淆。其主要应用在数据压缩,加密解密等场合。

哈弗曼树的C语言实现

<span style="font-size:18px;">#include <stdio.h>
#include <stdlib.h>

#define MAX 4

int input_weight(int *p)
{
    int i = 0;

    for(i = 0;i < MAX;i ++)
    {
        scanf("%d",p + i);
    }

    while(getchar()!= '\n');
        
    return 0;
}

int order_weight(int *p)
{
    int i = 0;
    int j = 0;
    int temp;

    for(i = 0;i < MAX;i ++)
    {
        for(j = 0;j < MAX - i - 1;j ++)
        {
            if(p[j] > p[j+1])
            {
                temp = p[j];
                p[j] = p[j+1];
                p[j+1] = temp;
            }
        }
    }

    return 0;
}

//哈夫曼树结点
typedef struct HuffNode
{
    int weight;
    struct HuffNode *rchild;
    struct HuffNode *lchild;
    
}HuffMan;

//队列设计
typedef struct _node_
{
    HuffMan *data;
    struct _node_ *next;
}ListNode;

typedef struct
{
    ListNode *front;
    ListNode *rear;
}Queue;

//create empty queue
Queue *create_empty_queue()
{
    ListNode *HList;
    Queue *Hqueue;

    HList = (ListNode *)malloc(sizeof(ListNode));
    HList->next = NULL;
    
    Hqueue = (Queue *)malloc(sizeof(Queue));
    Hqueue->front = Hqueue->rear = HList;

    return Hqueue;
}

//入队
int EnterQueue(Queue *head,HuffMan *data)
{
    ListNode *temp;

    temp = (ListNode *)malloc(sizeof(ListNode));
    temp->data = data;
    temp->next = NULL;

    head->rear->next = temp;
    head->rear = temp;

    return 0;
}

//有序插入结点
int OrderEnterQueue(Queue *head,HuffMan *p)
{
    ListNode *m = head->front->next;
    ListNode *n = head->front;
    ListNode *temp;
#if 0
    if(head->front->next == NULL)
    {
        printf("emty!\n");
        temp = (ListNode *)malloc(sizeof(ListNode));
        temp->data = p;
        temp->next = NULL;
        n->next = temp;
        head->rear = temp;
    }
#endif
    while(m)
    {
        if(m->data->weight < p->weight)
        {
            m = m->next;
            n = n->next;
        }
        else{
            
            break;
        }
    }

    //插到最后一个结点
    if(m == NULL)
    {
        temp = (ListNode *)malloc(sizeof(ListNode));
        temp->data = p;
        temp->next = NULL;
        n->next = temp;
        head->rear = temp;
    }

    //插入中间结点
    temp = (ListNode *)malloc(sizeof(ListNode));
    temp->data = p;
    n->next = temp;
    temp->next = m;

    return 0;
}

//判断队列是否为空(注意,我们认为队列含有一个结点为空,想想为什么
//这样做?
int is_empty_queue(Queue *head)
{
    if(head->front->next->next == NULL)
    {
        printf("is_empty_queue\n");
        return 1;
    }
    
    return 0;
}

//出队
HuffMan *DeleteQueue(Queue * head)
{
    ListNode *temp;

    temp = head->front;
    head->front = temp->next;
    free(temp);
    temp = NULL;

    return head->front->data;
}

//将结点按权值从小到大放入队列
int create_forest(Queue *head,int *p)
{
    int i = 0;
    HuffMan *temp;

    for(i = 0;i < MAX;i ++)
    {
        temp = (HuffMan *)malloc(sizeof(HuffMan));
        temp->weight = p[i];
        temp->rchild = temp->rchild = NULL;

        EnterQueue(head,temp);
    }

    return 0;
}

//创建哈夫曼树
HuffMan *create_huffman_tree(Queue *head)
{
    HuffMan *right,*left,*current;

    //循环结束时,队列只含有一个结点
    while(!is_empty_queue(head))
    {
        left = DeleteQueue(head);
        right = DeleteQueue(head);
        current = (HuffMan *)malloc(sizeof(HuffMan));
        current->weight = left->weight + right->weight;
        current->rchild = right;
        current->lchild = left;
#if 0
        printf("%d\n",left->weight);
        printf("%d\n",right->weight);
        printf("%d\n",current->weight);
#endif
        OrderEnterQueue(head,current);
        
    }

    return head->front->next->data;
}


//访问结点
int vist_node(HuffMan *p)
{
    printf("%d ",p->weight);

    return 0;
}

//树的中序遍历
int InOrder(HuffMan *p)
{
    if(p != NULL)
    {
        InOrder(p->lchild);//左
        vist_node(p);//根
        InOrder(p->rchild);//右
    }

    return 0;
}

int main()
{
    int Wbuf[MAX];
    Queue *head;
    HuffMan *root;

    //输入权值
    input_weight(Wbuf);
    //排序权值
    order_weight(Wbuf);
    //创建空队列
    head = create_empty_queue();
    //将结点按权值从小到大放入队列
    create_forest(head,Wbuf);
    //创建哈夫曼树
    root = create_huffman_tree(head);
    //中序遍历
    InOrder(root);
    printf("\n");
        
    return 0;
}</span>
<span style="font-size:18px;">结果显示:</span>

《数据结构&&哈弗曼树和哈弗曼编码》



哈弗曼编码C语言实现

<span style="font-size:18px;">#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//哈夫曼树结点
typedef struct HuffNode
{
    int weight;
    char ch;
    char code[20];
    struct HuffNode *rchild;
    struct HuffNode *lchild;
    
}HuffMan;

//队列设计
typedef struct _node_
{
    HuffMan *data;
    struct _node_ *next;
}ListNode;

typedef struct
{
    ListNode *front;
    ListNode *rear;
}Queue;

//create empty queue
Queue *create_empty_queue()
{
    ListNode *HList;
    Queue *Hqueue;

    HList = (ListNode *)malloc(sizeof(ListNode));
    HList->next = NULL;
    
    Hqueue = (Queue *)malloc(sizeof(Queue));
    Hqueue->front = Hqueue->rear = HList;

    return Hqueue;
}

//入队
int EnterQueue(Queue *head,HuffMan *data)
{
    ListNode *temp;

    temp = (ListNode *)malloc(sizeof(ListNode));
    temp->data = data;
    temp->next = NULL;

    head->rear->next = temp;
    head->rear = temp;

    return 0;
}

//有序插入结点
int OrderEnterQueue(Queue *head,HuffMan *p)
{
    ListNode *m = head->front->next;
    ListNode *n = head->front;
    ListNode *temp;

    while(m)
    {
        if(m->data->weight < p->weight)
        {
            m = m->next;
            n = n->next;
        }
        else{
            
            break;
        }
    }

    //插到最后一个结点
    if(m == NULL)
    {
        temp = (ListNode *)malloc(sizeof(ListNode));
        temp->data = p;
        temp->next = NULL;
        n->next = temp;
        head->rear = temp;

        return 0;
    }

    //插入中间结点
    temp = (ListNode *)malloc(sizeof(ListNode));
    temp->data = p;
    n->next = temp;
    temp->next = m;

    return 0;
}

//判断队列是否为空(注意,我们认为队列含有一个结点为空,想想为什么
//这样做?
int _is_empty_queue(Queue *head)
{
    if(head->front->next->next == NULL)
    {
        printf("is_empty_queue\n");
        return 1;
    }
    
    return 0;
}

//判断队列是否为空
int is_empty_queue(Queue *head)
{
    if(head->front == head->rear)
        return 1;
    else
        return 0;
}

//出队
HuffMan *DeleteQueue(Queue * head)
{
    ListNode *temp;

    temp = head->front;
    head->front = temp->next;
    free(temp);
    temp = NULL;

    return head->front->data;
}

//创建哈夫曼树
HuffMan *create_huffman_tree(Queue *head)
{
    HuffMan *right,*left,*current;

    //循环结束时,队列只含有一个结点
    while(!_is_empty_queue(head))
    {
        left = DeleteQueue(head);
        right = DeleteQueue(head);
        current = (HuffMan *)malloc(sizeof(HuffMan));
        current->weight = left->weight + right->weight;
        current->rchild = right;
        current->lchild = left;
        OrderEnterQueue(head,current);    
    }

    return head->front->next->data;
}

//哈夫曼编码
int HuffmanCode(HuffMan *root)
{
    HuffMan *current = NULL;
    Queue *queue = NULL;

    queue = create_empty_queue();

    EnterQueue(queue, root);

    while(!is_empty_queue(queue))
    {
        current = DeleteQueue(queue);

        if(current->rchild == NULL && current->lchild == NULL)
        {
            printf("%c:%d %s\n",current->ch,current->weight,current->code);
        }

        if(current->lchild)
        {
            strcpy(current->lchild->code,current->code);
            strcat(current->lchild->code,"0");
            EnterQueue(queue, current->lchild);
        }

        if(current->rchild)
        {
            strcpy(current->rchild->code,current->code);
            strcat(current->rchild->code,"1");
            EnterQueue(queue, current->rchild);
        }
    }

    return 0;
}</span>
<span style="font-size:18px;">结果显示:</span>

《数据结构&&哈弗曼树和哈弗曼编码》


    原文作者:哈夫曼树
    原文地址: https://blog.csdn.net/sp_programmer/article/details/40980039
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞