数据结构与算法之赫夫曼树

文章目录

赫夫曼树的概念

赫夫曼树:又称最优树,是一类带权路径长度最短的树,有着广泛的应用
1.最优二叉树(赫夫曼树)
首先给出路径和路径长度的概念,从树中的一个结点到另一个结点之间的分支构成这两个结点之间的路径,路径上的分支数目称作路经长度。树的路径长度是从树根到每一结点的路径长度之和。完全二叉树路径长度最短的二叉树。
在这里插入图片描述
赫夫曼树的建立:
不断地取最小的两个节点,构建成一棵树,然后将刚构建的树加入到数组中,不断的构建,最终构建出一棵树。
存储方式:静态存储
在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<stack>
#include <queue>
//静态存储
using namespace std;
const int n = 8; //leaf叶子的个数
const int m = n * 2; //node 节点个数
typedef unsigned int WeightType;
typedef unsigned int NodeType;
typedef struct
{
	WeightType weight;//权值
	NodeType parent, leftchild, rightchild;
}HTNode;

typedef HTNode HuffmanTree[m];

void PrintHuffmanTree(HuffmanTree hft)
{
	for (int i = 1; i < m; ++i)
	{
		printf("index %3d weight:%3d parent %3d Lchild %3d Rchild %3d\n",
			i, hft[i].weight, hft[i].parent, hft[i].leftchild, hft[i].rightchild);
	}
	printf("\n");
}
struct IndexWeigth
{
	int index;
	WeightType weight;
	operator WeightType()const { return weight; }
};
void CreateHuffmanTree(HuffmanTree hft)
{
	priority_queue<IndexWeigth,vector<IndexWeigth>,std::greater<IndexWeigth>>qu;//优先级队列,依次选择最小堆
	//每次取得第一小值
	for (int i = 1; i <= n; ++i)
	{
		qu.push(IndexWeigth{ i,hft[i].weight }); //将权值和下标放入队列
	}
	int k = n + 1;
	while (!qu.empty())
	{
		if (qu.empty())break;
		IndexWeigth left = qu.top(); qu.pop();
		if (qu.empty())break;
		IndexWeigth right = qu.top(); qu.pop();
		hft[k].weight = left.weight + right.weight;
		hft[k].leftchild = left.index;
		hft[k].rightchild = right.index;
		hft[left.index].parent = k;
		hft[right.index].parent = k;

		qu.push(IndexWeigth{ k,hft[k].weight });
		k += 1;
	}
}

void InitHuffmanTree(HuffmanTree hft, WeightType w[])
{
	memset(hft, 0, sizeof(HuffmanTree));
	for (int i = 0; i < n; ++i)
	{
		hft[i + 1].weight = w[i];
	}
}

int main()
{
	WeightType w[n] = { 5,29,7,8,14,23,3,11 };
	HuffmanTree hft = { 0 };
	InitHuffmanTree(hft, w);
	PrintHuffmanTree(hft);
	CreateHuffmanTree(hft);
	PrintHuffmanTree(hft);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

淡蓝色的经典

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

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

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

打赏作者

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

抵扣说明:

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

余额充值