最小スタックアプリケーション---最小スタックでhuffmanツリーを実現

2280 ワード

最小スタック応用---最小スタックでhuffmanツリーを実現し、huffmanは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;
}