数据结构 --- c语言实现哈夫曼树

本文介绍了哈夫曼树的结构体定义,包括节点、堆(小顶堆)的实现,以及关键函数如创建堆、调整堆、插入和出堆操作。同时涵盖了哈夫曼树的创建过程、节点连接和编码查找算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 哈夫曼树的结构体描述 

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define MAX 100
typedef struct huffmanTreeNode 
{
	int key;                               //键->出现的频率
    //char data;                           //当前频率对应的字符->方便做解码
	struct huffmanTreeNode* parentNode;    //记录树的父节点->方便连接操作
	struct huffmanTreeNode* LChild;        //左子树节点
	struct huffmanTreeNode* RChild;        //右子树节点
}NODE,*LPNODE,*LPTREE;

 准备一个堆存放节点--->堆的结构体描述

//小顶堆
typedef struct heap
{        
	int sizeHeap;                           //堆中元素个数
	LPNODE* heapData;                       //存储LPNODE的指针->存放多个一级指针用二级指针
}HEAP,*LPHEAP;

 创建堆--->数组实现 用结构体指针表示堆 

LPHEAP createHeap() 
{
	LPHEAP heap = (LPHEAP)malloc(sizeof(HEAP));
	assert(heap);
    //给数据做初始化
	heap->sizeHeap = 0;
	heap->heapData = (LPNODE*)malloc(sizeof(LPNODE) * MAX);
	return heap;
}

 万金油函数

int size(LPHEAP heap) 
{
	return heap->sizeHeap;
}
//判断堆是否为空
int empty(LPHEAP heap) 
{
	return heap->sizeHeap == 0;
}

 调整堆--->向上渗透

//要调整的堆 当前元素的下标
void moveTocorrectPos(LPHEAP heap, int curPos)
{
	while (curPos > 1)                                            //>1 一直往上冒渗透到下标[1]的位置
	{            
		LPNODE min = heap->heapData[curPos];                      //假设当前位置是最小的 与上面节点的值相比较
		int parentIndex = curPos / 2;                             //求出父节点的下标
		if (min->key < heap->heapData[parentIndex]->key)          //比较两个键 当前的键<父节点中的键就向上渗透
		{
			heap->heapData[curPos] = heap->heapData[parentIndex]; //交换父节点和子节点的值
			heap->heapData[parentIndex] = min;                    
			curPos = parentIndex;                                 //下标向1靠近
		}
		else                                                      //大于的情况说明放在了合适的位置 不用往上冒
		{
			break;
		}
	}
}

 堆的插入

//要插入的堆 要插入的数据
void insertHeap(LPHEAP heap, LPNODE data) 
{
    //存数据:直接放在当前数组后面即可 前置++第一个位置不存数据 存第1个元素放在[1]下标中
	heap->heapData[++heap->sizeHeap] = data;
    //向上渗透 调整堆
	moveTocorrectPos(heap, heap->sizeHeap);
}

 出堆--->向下渗透

//要出的堆 返回节点
LPNODE popHeap(LPHEAP heap) 
{
	LPNODE min = heap->heapData[1];                          //第一个元素肯定是最小的 下标为[1]的元素
	int curPos = 1;
	int childIndex = curPos * 2;
	while (childIndex <= heap->sizeHeap) 
	{
		LPNODE temp = heap->heapData[childIndex];
		//横向比较找最小值 只要比较横向的2个值 childPos + 1为右边的值
		if (childIndex + 1 <= heap->sizeHeap && temp->key > heap->heapData[childIndex + 1]->key) 
		{
			temp = heap->heapData[++childIndex];             //如果左边的值>边的值 需要往右走
		}
		//向下渗透
		heap->heapData[curPos] = temp;                       //如果往左边走 接着往下找即可
		curPos = childIndex;                                 //当前pos往下走
		childIndex *= 2;
	}
	heap->heapData[curPos] = heap->heapData[heap->sizeHeap]; //找到最终交换的元素
	moveTocorrectPos(heap, curPos);                          //存在不满足规则的情况做调整
	--heap->sizeHeap;
	return min;
}

 创建哈夫曼树的节点

//传入关键字
LPNODE createNode(int key) 
{
    //创建节点
	LPNODE newNode = (LPNODE)malloc(sizeof(NODE));
	assert(newNode);
    //给数据做初始化
	newNode->key = key;
	newNode->LChild = NULL;        //左右子树指针都指向NULL
	newNode->RChild = NULL;
	newNode->parentNode = NULL;    //单一节点没有父节点,父节点也指向NULL
	return newNode;
}

 构建哈夫曼子树的节点 从堆中挑两个最小的节点构成新的节点

//传入两个节点
LPNODE createhuffmanNode(LPNODE first, LPNODE second) 
{
	LPNODE parentNode = createNode(first->key + second->key);   //父节点的关键字=两个节点的关键字相加
    //比较节点哪个大,哪个小--->传入左边小右边大也可以
	LPNODE min = first->key > second->key ? second : first;     //左边
	LPNODE max = first->key > second->key ? first : second;     //右边
    //小的放左边 大的放右边
	parentNode->LChild = min;
	parentNode->RChild = max;
    //处理两个小节点的父节点->连接
	first->parentNode = parentNode;
	second->parentNode = parentNode;
	return parentNode;
}

 遍历哈夫曼树--->递归法遍历

//打印当前节点
void printCurNode(LPNODE curNode) 
{
	printf("%d\t", curNode->key);
}
void preOrder(LPTREE root) 
{
	if (root != NULL) 
	{
		printCurNode(root);
		preOrder(root->LChild);
		preOrder(root->RChild);
	}
}

 把数组的数据插到堆中去

//要插入的堆 
void insertArrayToHeap(LPHEAP heap, int array[], int arrayNum)
{
	for (int i = 0; i < arrayNum; i++) 
	{
		insertHeap(heap, createNode(array[i])); //把整个数组的元素都插进去了,插入的是哈夫曼树的节点不是int型数据
	}
}

 创建哈夫曼树--->通过数组创建树,传入数组长度

LPTREE createhuffmanTree(int array[], int arrayNum) 
{
	if (arrayNum <= 0)                       //数组长度<0返回NULL
		return NULL;
	else if (arrayNum == 1)       
		return createNode(array[0]);         //数组长度=1 返回1个节点
	else                                     //其他情况需要做树的构建
	{
		LPHEAP heap = createHeap();          //构建一个堆,需要先把数据插到堆中去,再从堆中挑两个最小的出来
		insertArrayToHeap(heap, array, arrayNum);
		LPTREE root = NULL;                  //根节点
        //从堆中挑两个最小的
		while (!empty(heap))                 //堆!=NULL出堆|从堆中挑两个最小的出来
		{
			LPNODE first = popHeap(heap);    //第一个元素出堆
			LPNODE second = popHeap(heap);   //第二个元素出堆
			root = createhuffmanNode(first, second);
			if (empty(heap))                 //如果堆刚好出完了,此时堆为空就没必要丢进去
				break;
			insertHeap(heap, root);          //把新节点丢到堆中去,再拿两个最小的出来
		}
		return root;
	}
}

查找某一个关键字

哈夫曼树的父节点与子节点没有关系,不能用递归的方式去查找,通过栈,要用回退的思想去做查找

不是边走边退,是左边走到底后,才开始出栈,找到节点后退出

LPNODE searchhuffmanTree(LPTREE tree, int key) 
{
	LPNODE pMove = tree;
	LPNODE stack[MAX];
	int top = -1;
	while (pMove != NULL || top != -1) 
	{
		while (pMove != NULL && pMove->key != key) 
		{
			stack[++top] = pMove;    //把走过的路径入栈
			pMove = pMove->LChild;   //先走左边走到底
		}
		if (pMove == NULL)           //=NULL退出循环 走到最左边
		{
			pMove = stack[top--];    //走到最左边,出栈
			pMove = pMove->RChild;   //出栈走右边去找
		}
		else if (pMove->key == key)  //找到了退出循环
		{
			break;
		}
	}
	return pMove;
}

打印哈夫曼编码--->每个编码都属于叶子层

假设传入叶子节点  5,让它依次往上走,走一个节点就入一次栈,走一个节点就入一次栈,[ 因为编码是从上往下走的,出栈的时候直接下来,把编码入栈后出栈即可 ] 走到 parentNode 为 NULL 的位置即可

void printCode(LPNODE leaf)
{
	LPNODE pMove = leaf;
	int stack[MAX];
	int top = -1;
	while (pMove!=NULL) 
	{
        //父节点不为空说明存在父节点 判断是父节点的左边还是右边
		if (pMove->parentNode != NULL && pMove->parentNode->LChild == pMove)
		{  
			stack[++top] = 0;       //如果是左子树入0
		}
		else if (pMove->parentNode != NULL && pMove->parentNode->RChild == pMove) 
		{ 
			stack[++top] = 1;       //如果是右子树入1
		}
		else                        //为空直接break->到达根部|只有根节点没有父节点
		{
			break;
		}
		pMove = pMove->parentNode;  //依次往上走
	}
	while (top != -1) 
	{
		printf("%d", stack[top--]); //出栈打印编码
	}
	printf("\n");
}
int main() 
{
	int array[] = { 7,4,5,2 };
	LPTREE tree = createhuffmanTree(array, 4);    //创建哈夫曼树
	printf("huffmanTree:\n");
	preOrder(tree);                               //先序打印
	printf("\nhuffman code:\n");
	for (int i = 0; i < 4; i++)                   //把每个节点的编码都打印出来
	{
		printf("%d:", array[i]);                  
		printCode(searchhuffmanTree(tree, array[i]));
	}
	return 0;
}

/*输出*/
huffmanTree:                                      //带权路径长度最小的二叉树
18    7    11    5    6    2    4                 
huffman code:                                     //打印每个数字的编码
7:0
4:111
5:10
2:110
#include #include #include #include using namespace std; # define MaxN 100//初始设定的最大结点数 # define MaxC 1000//最大编码长度 # define ImpossibleWeight 10000//结点不可能达到的权值 # define n 26//字符集的个数 //-----------哈夫曼的结点结构类型定义----------- typedef struct //定义哈夫曼各结点 { int weight;//权值 int parent;//双亲结点下标 int lchild;//左孩子结点下标 int rchild;//右孩子结点下标 }HTNode,*HuffmanTree;//动态分配数组存储哈夫曼 typedef char**HuffmanCode;//动态分配数组存储哈夫曼编码表 //-------全局变量-------- HuffmanTree HT; HuffmanCode HC; int *w;//权值数组 //const int n=26;//字符集的个数 char *info;//字符值数组 int flag=0;//初始化标记 //********************************************************************** //初始化函数 //函数功能: 从终端读入字符集大小n , 以及n个字符和n个权值,建立哈夫曼,并将它存于文件hfmTree中 //函数参数: //向量HT的前n个分量表示叶子结点,最后一个分量表示根结点,各字符的编码长度不等,所以按实际长度动态分配空间 void Select(HuffmanTree t,int i,int &s1,int &s2) { //s1为最小的两个值中序号最小的那个 int j; int k=ImpossibleWeight;//k的初值为不可能达到的最大权值 for(j=1;j<=i;j++) { if(t[j].weight<k&&t[j].parent==0) {k=t[j].weight; s1=j;} } t[s1].parent=1; k=ImpossibleWeight; for(j=1;j<=i;j++) { if(t[j].weight0),构造哈夫曼HT,并求出n个字符的哈弗曼编码HC { int i,m,c,s1,s2,start,f; HuffmanTree p; char* cd; if(num<=1) return; m=2*num-1;//m为结点数,一棵有n个叶子结点的哈夫曼共有2n-1个结点,可以存储在一个大小为2n-1的一维数组中 HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode));//0号单元未用 //--------初始化哈弗曼------- for(p=HT+1,i=1;iweight=*w; p->parent=0; p->lchild=0; p->rchild=0; } for(i=num+1;iweight=0; p->parent=0; p->lchild=0; p->rchild=0; } //--------哈夫曼------------- for(i=num+1;i<=m;i++) { Select(HT,i-1,s1,s2);//在HT[1...i-1]选择parent为0且weight最小的两个结点,其序号分别为s1和s2 HT[s1].parent=i; HT[s2].parent=i; HT[i].lchild=s1; HT[i].rchild=s2;//左孩子权值小,右孩子权值大 HT[i].weight=HT[s1].weight+HT[s2].weight; } //-------从叶子到根逆向求每个字符的哈弗曼编码-------- HC=(HuffmanCode)malloc((num+1)*sizeof(char *));//指针数组:分配n个字符编码的头指针向量 cd=(char*)malloc(n*sizeof(char*));//分配求编码的工作空间 cd[n-1]='\0';//编码结束符 for(i=1;i<=n;i++)//逐个字符求哈弗曼编码 { start=n-1;//编码结束符位置 for(c=i,f=HT[i].parent;f!=0;c=f,f=HT[f].parent)//从叶子到跟逆向求哈弗曼编码 if(HT[f].lchild==c) cd[--start]='0';//判断是左孩子还是右孩子(左为0右为1) else cd[--start]='1'; HC[i]=(char*)malloc((num-start)*sizeof(char*));//按所需长度分配空间 int j,h; strcpy(HC[i],&cd[start]); } free(cd); } //****************初始化函数****************** void Initialization() { flag=1;//标记为已初始化 int i; w=(int*)malloc(n*sizeof(int));//为26个字符权值分配空间 info=(char*)malloc(n*sizeof(char));//为26个字符分配空间 ifstream infile("ABC.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;i>info[i]; infile>>w[i]; } infile.close(); cout<<"读入字符成功!"<<endl; HuffmanCoding(HT,HC,w,n); //------------打印编码----------- cout<<"依次显示各个字符的值,权值或频度,编码如下"<<endl; cout<<"字符"<<setw(6)<<"权值"<<setw(11)<<"编码"<<endl; for(i=0;i<n;i++) { cout<<setw(3)<<info[i]; cout<<setw(6)<<w[i]<<setw(12)<<HC[i+1]<<endl; } //---------将建好的哈夫曼写入文件------------ cout<<"下面将哈夫曼写入文件"<<endl; ofstream outfile("hfmTree.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;i<n;i++,w++) { outfile<<info[i]<<" "; outfile<<w[i]<<" "; outfile<<HC[i+1]<<" "; } outfile.close(); cout<<"已经将字符与对应的权值,编码写入根目录下文件hfmTree.txt"<<endl; } //*****************输入待编码字符函数************************* void Input() { char string[100]; ofstream outfile("ToBeTran.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } cout<<"请输入你想要编码的字符串(字符个数应小于100),以#结束"<>string; for(int i=0;string[i]!='\0';i++) { if(string[i]=='\0') break; outfile<<string[i]; } cout<<"获取报文成功"<<endl; outfile.close(); cout<<"------"<<"已经将报文存入根目录下的ToBeTran.txt文件"<<endl; } //******************编码函数**************** void Encoding() { int i,j; char*string; string=(char*)malloc(MaxN*sizeof(char)); cout<<"下面对根目录下的ToBeTran.txt文件中的字符进行编码"<<endl; ifstream infile("ToBeTran.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;i>string[i]; } for(i=0;i<100;i++) if(string[i]!='#') cout<<string[i]; else break; infile.close(); ofstream outfile("CodeFile.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;string[i]!='#';i++) { for(j=0;j<n;j++) { if(string[i]==info[j]) outfile<<HC[j+1]; } } outfile<<'#'; outfile.close(); free(string); cout<<"编码完成------"; cout<<"编码已写入根目录下的文件CodeFile.txt中"<<endl; } //******************译码函数**************** void Decoding() { int j=0,i; char *code; code=(char*)malloc(MaxC*sizeof(char)); char*string; string=(char*)malloc(MaxN*sizeof(char)); cout<<"下面对根目录下的CodeFile.txt文件中的代码进行译码"<<endl; ifstream infile("CodeFile.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for( i=0;i>code[i]; if(code[i]!='#') { cout<<code[i]; } else break; } infile.close(); int m=2*n-1; for(i=0;code[i-1]!='#';i++) { if(HT[m].lchild==0) { string[j]=info[m-1]; j++; m=2*n-1; i--; } else if(code[i]=='1') m=HT[m].rchild; else if(code[i]=='0') m=HT[m].lchild; } string[j]='#'; ofstream outfile("TextFile.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } cout<<"的译码为------"<<endl; for( i=0;string[i]!='#';i++) { outfile<<string[i]; cout<<string[i]; } outfile<<'#'; outfile.close(); cout<<"------译码完成------"<<endl; cout<<"译码结果已写入根目录下的文件TextFile.txt中"<<endl; free(code); free(string); } //*************打印编码函数**************** void Code_printing() { int i; char *code; code=(char*)malloc(MaxC*sizeof(char)); cout<<"下面打印根目录下文件CodeFile.txt中的编码"<<endl; ifstream infile("CodeFile.txt",ios::in); if(!infile) { cerr<<"打开失败"<<endl; exit(1); } for( i=0;i>code[i]; if(code[i]!='#') cout<<code[i]; else break; } infile.close(); cout<<endl; ofstream outfile("CodePrin.txt",ios::out); if(!outfile) { cerr<<"打开失败"<<endl; exit(1); } for(i=0;code[i]!='#';i++) { outfile<<code[i]; } outfile.close(); free(code); cout<<"------打印结束------"<<endl; cout<<"该字符形式的编码文件已写入文件CodePrin.txt中"<<endl; } //*************打印哈夫曼函数**************** int numb=0; void coprint(HuffmanTree start,HuffmanTree HT) //start=ht+26这是一个递归算法 { if(start!=HT) { ofstream outfile("TreePrint.txt",ios::out); if(!outfile) { cerr<<"打开失败"<rchild,HT); //递归先序遍历 cout<<setw(5*numb)<weight<rchild==0) cout<<info[start-HT-1]<<endl; outfile<weight; coprint(HT+start->lchild,HT); numb--; outfile.close(); } } void Tree_printing(HuffmanTree HT,int num) { HuffmanTree p; p=HT+2*num-1; //p=HT+26 cout<<"下面打印赫夫曼"<<endl; coprint(p,HT); //p=HT+26 cout<<"打印工作结束"<<endl; } //*************主函数************************** int main() { char choice; do{ cout<<"************哈弗曼编/译码器系统***************"<<endl; cout<<"请选择您所需功能:"<<endl; cout<<":初始化哈弗曼"<<endl; cout<<":输入待编码字符串"<<endl; cout<<":利用已建好的哈夫曼进行编码"<<endl; cout<<":利用已建好的哈夫曼进行译码"<<endl; cout<<":打印代码文件"<<endl; cout<<":打印哈夫曼"<<endl; cout<<":退出"<<endl; if(flag==0) { cout<<"请先初始化哈夫曼,输入I"<<endl; cout<<""<>choice; switch(choice) { case 'I':Initialization();break; case 'W':Input();break; case 'E':Encoding();break; case 'D':Decoding();break; case 'P':Code_printing();break; case 'T':Tree_printing(HT,n);break; case 'Q':;break; default:cout<<"输入的命令出错,请重新输入!"<<endl; } }while(choice!='Q'); free(w); free(info); free(HT); free(HC); system("pause"); return 0; }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qiuqiuyaq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值