构造哈夫曼树并层次遍历

4 篇文章 0 订阅

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队列的表示和操作实现。

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值