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

1384人阅读 评论(0)

#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;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：284713次
• 积分：3925
• 等级：
• 排名：第8355名
• 原创：108篇
• 转载：25篇
• 译文：0篇
• 评论：69条
最新评论
文章收藏