// Huffman tree node abstract base class template <typename E> classHuffNode { public: virtual ~HuffNode() {} // Base destructor virtualintweight()= 0; // Return frequency virtualboolisLeaf()= 0; // Determine type }; template <typename E> // Internal node subclass classIntlNode : public HuffNode<E> { private: HuffNode<E>* lc; // Left child HuffNode<E>* rc; // Right child int wgt; // Subtree weight public: IntlNode(HuffNode<E>* l, HuffNode<E>* r) { wgt = l->weight() + r->weight(); lc = l; rc = r; } intweight(){ return wgt; } boolisLeaf(){ returnfalse; } HuffNode<E>* left()const{ return lc; } voidsetLeft(HuffNode<E>* b) { lc = (HuffNode<E>*)b; } HuffNode<E>* right()const{ return rc; } voidsetRight(HuffNode<E>* b) { rc = (HuffNode<E>*)b; } }; template <typename E> // Leaf node subclass classLeafNode : public HuffNode<E> { private: E it; // Value int wgt; // Weight public: LeafNode(const E& val, int freq) // Constructor { it = val; wgt = freq; } intweight(){ return wgt; } E val(){ return it; } boolisLeaf(){ returntrue; } };
单击此处查看Huffman树的类说明
下面是从教材中摘录的Huffman树的类说明。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// HuffTree is a template of two parameters: the element // type being coded and a comparator for two such elements. template <typename E> classHuffTree { private: HuffNode<E>* Root; // Tree root public: HuffTree(E& val, int freq) // Leaf constructor { Root = newLeafNode<E>(val, freq); } // Internal node constructor HuffTree(HuffTree<E>* l, HuffTree<E>* r) { Root = newIntlNode<E>(l->root(), r->root()); } ~HuffTree() {} // Destructor HuffNode<E>* root(){ return Root; } // Get root intweight(){ return Root->weight(); } // Root weight };
// Build a Huffman tree from a collection of frequencies template <typename E> HuffTree<E>* buildHuff(HuffTree<E>** TreeArray, int count){ heap<HuffTree<E>*,minTreeComp>* forest = new heap<HuffTree<E>*, minTreeComp>(TreeArray, count, count); HuffTree<char> *temp1, *temp2, *temp3 = NULL; while (forest->size() > 1) { temp1 = forest->removefirst(); // Pull first two trees temp2 = forest->removefirst(); // off the list temp3 = newHuffTree<E>(temp1, temp2); forest->insert(temp3); // Put the new tree back on list delete temp1; // Must delete the remnants delete temp2; // of the trees we created } return temp3; }