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