#include <iostream>
#include<string>
using namespace std;
struct HuffManNode {
string data;
int parent{};
int leftChild{};
int rightChild{};
int weight{};
};
void findTheSmallest(HuffManNode tree[], int range, int &target1, int &target2) {
//找一个没有双亲的结点赋值给target1
for (int i = 1; i <= range; ++i) {
if (tree[i].parent == 0) {
target1 = i;
break;
}
}
for (int i = 1; i <= range; ++i) {
if (tree[i].parent != 0) {
continue;
} else if (tree[i].weight < tree[target1].weight) {
target1 = i;
}
}
//找一个没有双亲的结点赋值给target2且target2 != target1
for (int i = 1; i <= range; ++i) {
if (tree[i].parent == 0 && i != target1) {
target2 = i;
break;
}
}
for (int i = 1; i <= range; ++i) {
if (tree[i].parent != 0) {
continue;
} else if (tree[i].weight < tree[target2].weight && i != target1) {
target2 = i;
}
}
}
void buildHuffManTree(HuffManNode *&tree, int nodeNum) {
//对二叉树的节点进行初始化
int allNodeNum = 2 * nodeNum - 1; //2n-1
tree = new HuffManNode[allNodeNum + 1];
for (int i = 1; i <= allNodeNum; ++i) {
tree[i].rightChild = 0;
tree[i].leftChild = 0;
tree[i].parent = 0;
tree[i].weight = 0;
}
//对二叉树进行输入
for (int j = 1; j <= nodeNum; ++j) {
string inputString;
int inputWeight;
cout << "请输入第" << j << "组的数据、权重:";
cin >> inputString >> inputWeight;
tree[j].data = inputString;
tree[j].weight = inputWeight;
}
//开始构建二叉树
int target1;
int target2;
for (int k = nodeNum + 1; k <= allNodeNum; ++k) {
//选取权重最小的双亲为0的两个节点的下标
findTheSmallest(tree, k - 1, target1, target2);
tree[target1].parent = k;
tree[target2].parent = k;
tree[k].leftChild = target1;
tree[k].rightChild = target2;
tree[k].weight = tree[target1].weight + tree[target2].weight;
}
}
void travelHuffManTree(HuffManNode *&tree, int targetPosition) {
cout << tree[targetPosition].weight << " 、";
if (tree[targetPosition].leftChild != 0) {
travelHuffManTree(tree, tree[targetPosition].leftChild);
}
if (tree[targetPosition].rightChild != 0) {
travelHuffManTree(tree, tree[targetPosition].rightChild);
}
}
void codingHuffManTree(HuffManNode *&tree, int targetPosition, const string &codingData) {
if (tree[targetPosition].rightChild == 0 && tree[targetPosition].leftChild == 0) {
cout << tree[targetPosition].data << " : " << codingData << endl;
} else {
string data = codingData + "0";
codingHuffManTree(tree, tree[targetPosition].leftChild, codingData + "0");
codingHuffManTree(tree, tree[targetPosition].rightChild, codingData + "1");
}
}
int main() {
int nodeNum;
cout << "请输入结点个数:";
cin >> nodeNum;
HuffManNode *tree1;
cout << "开始构建哈夫曼树......" << endl;
buildHuffManTree(tree1, nodeNum);
cout << "构建完成!" << endl;
cout << "先序遍历输出哈弗曼树各结点的权:";
travelHuffManTree(tree1, 2 * nodeNum - 1);
cout<<"正在对哈弗曼树进行编码......"<<endl;
codingHuffManTree(tree1, 2*nodeNum-1,"");
}
构造哈弗曼树并写出编码
最新推荐文章于 2021-07-15 16:41:42 发布