您的位置:首页 > 理论基础 > 数据结构算法

2015-8-19数据结构学习-哈夫曼树

2015-08-19 17:27 495 查看
// 哈夫曼树.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"

#include<iostream>

#define N 6

#define M 2*N-1

#define EPS 1e-5

#define random(x) (rand()%x)

using namespace std;

typedef char datatype;

typedef struct{
float weight;
datatype data;
int lchild, rchild, parent;

}hufmtree;

hufmtree tree1[M];

float weights[] = {0.4,0.3,0.1,0.1,0.02,0.08};

void Huffman(hufmtree tree[]){
int i, j, p1, p2;
char ch;
float small1, small2, f;//small1,small2是一轮搜索(除去已搜索的)权值最小的两个
for (int i = 0; i < N; i++){
tree[i].data = 'A' + i;
tree[i].weight = weights[i];
tree[i].parent = -1;
tree[i].lchild = -1;
tree[i].rchild = -1;
cout <<i<<"   "<< tree[i].data << "   " << tree[i].weight << endl;
}
for (int i = N; i < M; i++){
p1 = p2 = 0;//记下两个权值最小   —树数组下标
small1 = small2 = 10000.0;
for (int j = 0; j < i; j++){
if (tree[j].parent == -1){
if (tree[j].weight< small1)
{
small2 = small1;
small1 = tree[j].weight;
p2 = p1;
p1 = j;
continue;
}
else if (tree[j].weight<small2){
small2 = tree[j].weight;
p2 = j;
}
}//if
}//for
cout << "p1=" << p1 << "  p2=" << p2<<endl;
tree[p1].parent = i;
tree[p2].parent = i;
tree[i].lchild = p1;
tree[i].rchild = p2;
tree[i].parent = -1;
tree[i].weight = tree[p1].weight + tree[p2].weight;

}

}

int _tmain(int argc, _TCHAR* argv[])

{
Huffman(tree1);
for (int i = 0; i < M; i++){

cout <<i<<"    "<< tree1[i].data << "   " << tree1[i].weight << "  parent=" << tree1[i].parent<< endl;
}
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息