数据结构与算法基础之哈夫曼树(C语言)
学习来源:
数据结构与算法基础(青岛大学-王卓)
地址:
https://www.bilibili.com/video/BV1nJ411V7bd?p=22&spm_id_from=pageDriver
背景:
实现视频里老师的伪代码,并不完全一样,但基本雷同。
更新
2021/8/1
第一次发布
代码:
Huffman.h
#ifndef _HUFFMAN_H_
#define _HUFFMAN_H_
typedef struct Huffman *Huffman;
//Create a Huffman tree that have "warrLen" leaf nodes.
Huffman Create_Huffman(int warr[], unsigned warrLen);
//Destroy Huffman tree, "hfmP" will be set NULL.
void Destroy_Huffman(Huffman *hfmP);
//Show Huffman tree nodes.
void Show_Huffman(Huffman hfm);
#endif
Huffman.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Huffman.h"
#include "CommonFunc.h"
typedef struct
{
int weight;//Each node's weright.
int parent;//Each node's parent node's index.
int left;//Each node's left child node's index.
int right;//Each node's right child node's index.
} HNode;
struct Huffman
{
HNode *HNArr;//Huffman tree's nodes.
unsigned HuffmanLen;//Huffman tree length.
int *HNArrP;//As a tool to soft the tree from weight.
};
//Get the available node amount from Huffman tree "hfm".
static unsigned GetNodeLen_Huffman(Huffman hfm);
//Fill the Huffman tree.
static void FillHuffman(Huffman hfm);
//Sort Huffman tree by weight.
static void Sort_Huffman(Huffman hfm);
//Show Huffman tree nodes' weight after sort.
static void ShowSort_Huffman(Huffman hfm);
//Swap
static void Swap_Huffman(int *a, int *b);
//Get left and right child write into "L" and "R".
static int GetChildren_Huffman(Huffman hfm, int *L, int *R);
static int GetChildren_Huffman(Huffman hfm, int *L, int *R)
{
NULLPointOut(hfm, "GetChildren_Huffman", "hfm");
NULLPointOut(L, "GetChildren_Huffman", "L");
NULLPointOut(R, "GetChildren_Huffman", "R");
HNode *HNArr = hfm->HNArr;
int *HNArrP = hfm->HNArrP;
unsigned n = GetNodeLen_Huffman(hfm);
int arr[2];
unsigned j = 0;
unsigned i;
for(i = 0; i < n && j < 2; i++)
{
if(HNArr[HNArrP[i]].parent == -1)
{
arr[j] = HNArrP[i];
j++;
}
}
if(j < 2)
{
return 0;
}
*L = arr[0];
*R = arr[