fuliangliang的Blog

合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。

最小堆应用---用最小堆实现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;
}

阅读更多
文章标签: class null
上一篇常用类之三----最小堆实现优先队列
下一篇最小(大)堆应用---堆排序
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭