哈夫曼树的构建代码
输入一个字符串,构建相应的哈夫曼树,输出WPL。
#include <iostream>
#include<cstdio>
#include<cstring>
#include<stdlib.h>
using namespace std;
#define INF 0x3f3f3f3f
const int N=1010;
typedef struct //HuffmanTree
{
int weight;
int depth;
int parent,lchild,rchild;
}HTNode,*HuffmanTree;
void Select(HuffmanTree &ht,int q,int &n,int &m); //选择最小的两个数s1,s2
void CreateHuffman(HuffmanTree &ht,int n,int b[]) //构建哈法曼树
{
if(n<=1)return ;
int m=2*n-1;
ht=(HuffmanTree)malloc(sizeof(HTNode)*m);
for(int i=1;i<m;i++)
{
ht[i].depth=0;
ht[i].lchild=0;
ht[i].rchild=0;
ht[i].parent=0;
}
for(int i=1;i<=n;i++)
ht[i].weight=b[i-1];
int s1,s2;
for(int i=n+1;i<=m;i++)
{
Select(ht, i - 1, s1, s2);
ht[s1].parent=