#include <iostream> #include <vector> #include <algorithm> #include <string> usingnamespace std; //the structure of the Huffman tree's nodes typedef struct HFNode ...{ int data; struct HFNode* pLChild; struct HFNode* pRChild; }HFNode; HFNode EmptyNode = ...{ 0, NULL, NULL }; //creat the rule for the sort() to compare all the elements in the vector bool SortRule(HFNode& a, HFNode& b) ...{ if (a.data <= b.data) returntrue; else returnfalse; } //use the preprocessor operator ## to creat the variables #define pHFNode(j) pHFNode##j //print all the elements of the HFTree according pre order void PreOrderPrint(HFNode* pRoot) ...{ if (NULL != pRoot) cout << pRoot->data << endl; if (NULL != pRoot->pLChild) PreOrderPrint(pRoot->pLChild); else cout <<"@"<< endl; if (NULL != pRoot->pRChild) PreOrderPrint(pRoot->pRChild); else cout <<"@"<< endl;; } int main() ...{ constint NODENUM =4; vector<HFNode> HFArray (NODENUM, EmptyNode); int ValueArray[NODENUM] =...{7, 5, 2, 4}; //provide data for all the nodes for (int i =1; i <= NODENUM; i++) ...{ HFArray[i -1].data = ValueArray[i -1]; } int a, b, c ; a = b = c =1; while(HFArray.size() >1) ...{ //sort the vector and find the first and second of the smallest nodes sort(HFArray.begin(), HFArray.end(), SortRule); HFNode* pHFNode(a) =new HFNode; memcpy(pHFNode(a), &HFArray[0], sizeof(HFNode)); a++; HFNode* pHFNode(b) =new HFNode; memcpy(pHFNode(b), &HFArray[1], sizeof(HFNode)); b++; //creat the node as a root for the selected two leaf nodes HFNode* pHFNode(c) =new HFNode; pHFNode(c)->data = pHFNode(a)->data + pHFNode(b)->data; pHFNode(c)->pLChild = pHFNode(a); pHFNode(c)->pRChild = pHFNode(b); c++; //erase the two nodes and push back the new root HFArray.erase(HFArray.begin(), HFArray.begin() +2); HFArray.push_back(*pHFNode(c)); } HFNode Root = HFArray.front(); PreOrderPrint(&Root); getchar(); }