C++构造哈夫曼树并层序遍历
算法思想及代码全部来自《数据结构(C语言版)》(第2版)第5章,5.7哈夫曼树及其应用和第3章,3.5队列的表示和操作实现,中所讲的内容。
#include<iostream>
#include<algorithm>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int ElemType;
#define MAXSIZE 100
typedef struct
{
int weight;
int parient,lchild,rchild;
}HTNode,*HuffmanTree;//哈夫曼树储存结构
typedef struct
{
int *base;
int front;
int rear;
}SqQueue;//循环队列储存结构
int InitQueue(SqQueue &Q)
{
Q.base=new ElemType[MAXSIZE];
if(!Q.base) exit(OVERFLOW);
Q.front=Q.rear=0;
return OK;
}//循环队列初始化
int EnQueue(SqQueue &Q,int e)
{
if((Q.rear+1)%MAXSIZE==Q.front)
return ERROR;
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%MAXSIZE;
return OK;
}//入队
int DeQueue(SqQueue &Q,int &e)
{
if(Q.front==Q.rear) return ERROR;
e=Q.base[Q.front];
Q.front=(Q.front+1)%MAXSIZE;
return OK;
}//出队
int Select(HuffmanTree &HT,int n)
{
int i=1,t,x;
while(HT[i].parient!=0)
{
i++;
}
t=HT[i].weight;
x=i;
for(i;i<=n;i++)
{
if(t>HT[i].weight&&HT[i].parient==0)
{
t=HT[i].weight;
x=i;
}
}
return x;
}//返回父母为0的最小权值的序号
void CreateHuffmanTree(HuffmanTree &HT,int n)
{
if(n<=1) return;
int m=2*n-1;
HT=new HTNode[m+1];
int i;
for(i=1;i<m;++i)
{
HT[i].parient=0;
HT[i].lchild=0;
HT[i].rchild=0;
}//初始化哈夫曼树
for(i=1;i<=n;++i)
{
cin>>HT[i].weight;
}//输入哈夫曼树的权值
for(i=n+1;i<=m;++i)
{
int s1,s2;
s1=Select(HT,i-1);
HT[s1].parient=i;
s2=Select(HT,i-1);
HT[s2].parient=i;
HT[i].lchild=s2;
HT[i].rchild=s1;
HT[i].weight=HT[s1].weight+HT[s2].weight;
}
}//构造哈夫曼树
void PrintHuffmanTree(HuffmanTree &HT,int n)
{
SqQueue Q;
InitQueue(Q);
int m,e;
m=2*n-1;
e=m;
if(HT[e].lchild!=0)
{
cout<<HT[e].weight<<" ";
int x;
x=HT[e].lchild;
EnQueue(Q,x);
x=HT[e].rchild;
EnQueue(Q,x);
}
DeQueue(Q,e);
cout<<HT[e].weight<<" ";
while(Q.front!=Q.rear)
{
if(HT[e].lchild!=0)
{
int x;
x=HT[e].lchild;
EnQueue(Q,x);
x=HT[e].rchild;
EnQueue(Q,x);
}
DeQueue(Q,e);
cout<<HT[e].weight<<" ";
}
delete Q.base;
}//层序遍历哈夫曼树
int main(void)
{
HuffmanTree HT;
int n;
cin>>n;
CreateHuffmanTree(HT,n);
PrintHuffmanTree(HT,n);
delete HT;
}//程序源代码来自《数据结构(C语言版)》(第2版)人民邮电出版社,第五章,5.7哈夫曼树及其应用和第三章3.5队列的表示和操作实现。