Huffman树

Huffman树,又称最优二叉树,是一类加权路径长度最短的二叉树

路径:从树中一个结点到另一个结点之间的分支构成该两结点之间的路径

路径长度:路径上分支条数

#ifndef HUFFMAN_H
#define HUFFMAN_H

#include"MinHeap.h"

class HuffmanNode{
public:
float data;
HuffmanNode *leftChild,*rightChild,*parent;
HuffmanNode():leftChild(NULL),rightChild(NULL),parent(NULL){}
HuffmanNode(float elem,HuffmanNode* left=NULL,
HuffmanNode* right=NULL,HuffmanNode* pr=NULL)
:data(elem),leftChild(left),rightChild(right),parent(pr){}
bool operator<=(HuffmanNode& R){
return data<=R.data;
}
bool operator>(HuffmanNode& R){
return data>R.data;
}
};

class HuffmanTree{
public:
HuffmanTree(float w[],int n);
~HuffmanTree(){
delete root;
}
protected:
HuffmanNode* root;
void deleteTree(HuffmanNode* t);
void mergeTree(HuffmanNode& ht1,HuffmanNode& ht2,HuffmanNode*& parent);
};

HuffmanTree::HuffmanTree(float w[], int n)
{
MinHeap<HuffmanNode> hp;
HuffmanNode* parent,first,second,work;
for(int i=0;i<n;++i){
work.data=w[i];
work.leftChild=NULL;
work.rightChild=NULL;
work.parent=NULL;
hp.Insert(work);
}
for(int i=0;i<n-1;++i){
hp.RemoveMin(first);
hp.RemoveMin(second);
mergeTree(first,second,parent);
hp.Insert(*parent);
}
root = parent;
}

void HuffmanTree::mergeTree(HuffmanNode &bt1, HuffmanNode &bt2, HuffmanNode *&parent)
{
parent = new HuffmanNode;
parent->leftChild = &bt1;
parent->rightChild = &bt2;
parent->data = bt1.data+bt2.data;
bt1.parent = bt2.parent = parent;
}

#endif // HUFFMAN_H

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值