#include <iostream>using namespace STD;structhaffnode{intData Haffnode *left; Haffnode *right; Haffnode *parent; Haffnode (intD =int()):d ATA (d), left (null), Right (NULL), parent (null) {}BOOL operator> (ConstHaffnode &node) {//heavy load, convenient for minimum heap generation. returnData > Node.data; }};Template<intNTypeNameT>classmixhash{ Public: Mixhash () {*hashval =NewT[n]; CurrentSize =0; } ~mixhash () {if(*hashval)Delete[] *hashval;//destructor two-dimensional array, two-dimensional array of nodes inside the Haffman tree inside the destruction of the release. }voidInsert (T *val) {hashval[currentsize++] = val;intn = currentsize/2; while(N >=0) {adjust (hashval,n); n--; } }voidAdjust (T *hashval[],intN//Minimum heap regeneration. {inti = n;intj = i *2+1; while(J < CurrentSize) {if(j+1<currentsize && (*hashval[j]) > (*hashval[j +1])) J = j +1;if((*hashval[i]) > (*hashval[j])) {T *temp = hashval[i]; Hashval[i] = Hashval[j]; HASHVAL[J] = temp; } i = J; j = i *2+1; }} t *getnode () {T *temp = hashval[0]; hashval[0] = Hashval[--currentsize]; Adjust (hashval,0);returnTemp }BOOLIsOk () {returnCurrentSize = =1; }Private: T *hashval[n];//Alas, starting with a one-dimensional array, the node passed in is a pointer, the node pointer assignment object must be dereferenced, //Then quite with the save N objects, when I am in the exchange, there is no deep copy, so the exchange is not thorough, //When I return to the address, or the original address, there is no change, so I think with a two-dimensional array, is //pointer array, so that the array contains the actual node pointers, I can directly manipulate these pointers as the tree //node. intCurrentSize;};Template<intN>classhafftree{ Public: Hafftree (): root (NULL) {}voidInsert (intA[],intN) { for(inti =0; I < n; i++) {Haffnode *s =NewHaffnode (A[i]); Mh. Insert (s); }} ~hafftree () {DELETE (root); }voidDELETE (Haffnode *&t) {if(t = = NULL)return;Else{DELETE (t->left); DELETE (T->right);DeleteT t = NULL;//Empty to prevent wild hands. } }voidCreate ()//Start constructing the Haffman tree. { while(!MH. IsOk ())//The last node left is the last Haffman tree. {Haffnode *node1 = mh. GetNode (); Haffnode *node2 = mh. GetNode (); Haffnode *newnode =NewHaffnode (Node1->data + node2->data); Newnode->right =node2;//Start connection construction. Node2->parent = NewNode; Newnode->left = Node1; Node1->parent = NewNode; Mh. Insert (NewNode);//Insert minimum heap, continue selection. root = NewNode; } }voidprintf () {printf (root); }Private:voidPrintf (Haffnode *t) {if(t = = NULL)return;Else{cout<< T->data <<" "; Printf (T->left); Printf (T->right); } }Private: Haffnode *root; Mixhash<n, haffnode> MH;//Maintain a minimum heap. };intMain () {intA[] = {1,2,3,4,5}; hafftree<sizeof(a)/sizeof(int) > HT; Ht. Insert (A,sizeof(a)/sizeof(int)); Ht. Create (); Ht. Printf ();}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Data structure: Haffman tree