请给出哈夫曼树的建树代码
时间: 2024-03-10 07:19:13 浏览: 54
以下是哈夫曼树的 C++ 代码:
```
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// 哈夫曼树节点
struct HuffmanNode
{
int weight; // 权值
int parent; // 父节点下标
int leftChild; // 左子节点下标
int rightChild; // 右子节点下标
};
// 根据权值比较大小的仿函数
struct HuffmanCmp
{
bool operator() (HuffmanNode a, HuffmanNode b)
{
return a.weight > b.weight;
}
};
// 建立哈夫曼树
void BuildHuffmanTree(int* weight, int n, HuffmanNode* nodes)
{
// 创建权值最小的优先队列
priority_queue<HuffmanNode, vector<HuffmanNode>, HuffmanCmp> q;
for(int i = 0; i < n; ++i)
{
nodes[i].weight = weight[i];
nodes[i].parent = -1;
nodes[i].leftChild = -1;
nodes[i].rightChild = -1;
q.push(nodes[i]);
}
// 构建哈夫曼树
for(int i = 0; i < n-1; ++i)
{
// 取出权值最小的2个节点
HuffmanNode node1 = q.top(); q.pop();
HuffmanNode node2 = q.top(); q.pop();
// 创建新节点,左右指针分别指向取出的2个节点
HuffmanNode newNode = {node1.weight + node2.weight, -1, node1.weight < node2.weight ? node1 : node2, node1.weight < node2.weight ? node2 : node1};
// 设置取出的2个节点的父节点指针
node1.parent = i + n;
node2.parent = i + n;
// 将新节点加入队列
q.push(newNode);
// 新节点指向父节点
nodes[i+n] = newNode;
}
}
int main()
{
int n = 5;
int weight[5] = {5, 2, 4, 7, 1};
HuffmanNode nodes[2*n-1];
BuildHuffmanTree(weight, n, nodes);
return 0;
}
```
阅读全文