@【数据结构】(二叉树-哈夫曼编码)

@【数据结构】(二叉树-哈夫曼树及哈夫曼编码)

实现哈夫曼树的创建算法,并按哈夫曼树实现哈夫曼编码算法。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<iomanip>
#define MAXVALUE 10000
#define MAXLEAF 30       // 叶子结点数
#define MAXNODE MAXLEAF*2-1    //树中结点总数
using namespace std;

typedef struct
{
	int weight;
	int parent;
	int lchild;
	int rchild;
}Hnode, HuffmanTree[MAXNODE];
typedef struct codenode
{
	char ch;     //存放要表示的符号
	char code[MAXLEAF];  // 存放相应代码
}CodeNode;
typedef CodeNode HFCode[MAXLEAF];

void createHT(HuffmanTree ht, int w[], int n) // w传递n个权值
{
	int i, j, m1, m2, x1, x2;
	for (i = 0; i < 2 * n-1; i++)    // 所有结点的相关域置初值-1
	{
		ht[i].parent = ht[i].lchild = ht[i].rchild = 0;
		ht[i].weight = 0;
	}
	//赋权值
	for (i = 0; i < n; i++)
		ht[i].weight = w[i];
	for (i = 0; i < n-1 ; i++)
	{
		m1 = m2 = MAXVALUE;
		x1 = x2 = 0;
		for (j = 0; j <n + i; j++)   // 寻找权值最小的两颗子树
		{
			if (ht[j].weight < m1&&ht[j].parent == 0)
			{
				m2 = m1; x2 = x1; x1 = j;
				m1 = ht[j].weight;      // 次小
			}
			else if (ht[j].weight < m2&&ht[j].parent == 0)
			{
				m2 = ht[j].weight;
				x2 = j;                //最小
			}
		}
		//将找出的两颗子树合并为一颗子树
		ht[x1].parent = n + i; ht[x2].parent = n + i;
		ht[n + i].weight = ht[x1].weight + ht[x2].weight;
		ht[n + i].lchild = x1;
		ht[n + i].rchild = x2;
	}
}
void outputTree(HuffmanTree ht,int n)
{
	cout <<  "序号 weight parent leftchild  rightchild" << endl;
	for (int i = 0; i < n * 2-1; i++)
	{
		cout << setw(3) << i;
		cout << setw(4) << ht[i].weight;
		cout << setw(4) << ht[i].parent;
		cout << setw(4) << ht[i].lchild;
		cout << setw(4) << ht[i].rchild << endl;
	}
	cout << endl;
}
void createHFCode(HuffmanTree ht, HFCode &hc, int n)  //从叶子到根,逆向搜索
{
	char code[10];
	int i, c, p, start;
	cout << "输入相应待编码字符(8):" << endl;
	for (i = 0; i < n; i++)
		cin >> hc[i].ch;
	code[n - 1] = '\0';    // 从左到右逐位存放编码,首先存放结束符
	for (i =0; i <= n; i++)    //求n个结点对应的哈夫曼编码
	{
		start = n - 1;
		c = i; p = ht[i].parent;
		while (p != 0)
		{
			--start;
			if (ht[p].lchild == c)  // 左子树
				code[start] = '0';
			else code[start] = '1';   //右子树
			c = p;
			p = ht[p].parent;   //向上倒推
		}
		strcpy(hc[i].code, &code[start]);    // 将工作区中的编码复制到编码表中
	}
}
void outputCode(HFCode hc, int n)
{
	for (int i = 0; i <n ; i++)
	{
		cout << hc[i].ch << "->" << hc[i].code << endl;
	}
	cout << endl;
}
void main()
{
	HuffmanTree ht;
	HFCode hc;
	int w[10];
	int i, j, n;
	cout << "请输入哈弗曼树叶子结点的权值(8):" << endl;
	for (i = 0; i < 8; i++)
		cin >> w[i];
	createHT(ht, w,8);
	outputTree(ht, 8);
	createHFCode(ht, hc, 8);
	outputCode(hc, 8);
	system("pause");
}

测试:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值