赫夫曼树,又称最优二叉树,是一类带权值路径长度最短的树,有着广泛的应用。
代码:
/*
数据结构之赫夫曼树及求最优带权路径长度(带权路径长度:WPL)
思路:
自底向上,优先合并权值小的结点。合并后,双亲结点权值设为两子结点之和,忽略被合并的结点,
如此重复至所有结点都归入一棵树
*/
#include<stdio.h>
#include<stdlib.h>
#include <malloc.h>
typedef int ElemType;
typedef struct HFTreeNode{
ElemType data;
struct HFTreeNode* left;
struct HFTreeNode* right;
}HFTreeNode,*p_Huffman;
p_Huffman CreateTree(ElemType arr[],int len){
p_Huffman ptrArr[len];
p_Huffman ptr;
p_Huffman p_res;
int i;
if(len == 1){
p_res = (p_Huffman)malloc(sizeof(HFTreeNode));
p_res->data = arr[len-1];
p_res->left = p_res->right = NULL;
return p_res;
}
for (i = 0; i < len; i++){
ptr = (p_Huffman)malloc(sizeof(HFTreeNode));
ptr->data = ar