# 最小堆应用---用最小堆实现huffman树

#include"MinHeap.h"

template<class T> class HuffmanTree;
template<class T>
class TreeNode{
friend class HuffmanTree<T>;
private:
T data;
TreeNode<T> *left,*right;
public:
TreeNode(T value){
data = value;
left = right = NULL;
}
TreeNode(){
left = right = NULL;
}
bool operator > (const TreeNode &node){
return data > node.data;
}
bool operator < (const TreeNode &node){
return data < node.data;
}
bool operator == (const TreeNode &node){
return data == node.data;
}
bool operator >= (const TreeNode &node){
return data >= node.data;
}
};

template <class T>
class HuffmanTree{
public:
HuffmanTree();
HuffmanTree(T value[],int n);
protected:
TreeNode<T> *JoinTree(TreeNode<T> &node1,TreeNode<T> &node2);
TreeNode<T> *root;
};

template<class T>
HuffmanTree<T>::HuffmanTree():root(NULL){
}

template<class T>
HuffmanTree<T>::HuffmanTree(T value[],int n):root(NULL){
TreeNode<T> *nodes = new TreeNode<T>[n];
TreeNode<T> leftNode,rightNode;
int i = 0;
for(i = 0; i < n; i++){
nodes[i] = TreeNode<T>(value[i]);
}
MinHeap< TreeNode<T> > *m_heap = new MinHeap< TreeNode<T> >(nodes,n);

for(i = 0; i < n-1; i++){
m_heap->RemoveMin(leftNode);
m_heap->RemoveMin(rightNode);
root = JoinTree(leftNode,rightNode);
m_heap->Insert(*root);
}
}

template<class T>
TreeNode<T> *HuffmanTree<T>::JoinTree(TreeNode<T> &node1,TreeNode<T> &node2){
TreeNode<T> *r = new TreeNode<T>;
r->left = &node1;
r->right = &node2;
r->data = node1.data + node2.data;
return r;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：最小堆应用---用最小堆实现huffman树 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)