最优归并模式——自己实现的霍夫曼树

#include "stdafx.h" #include<iostream> #include<queue> #include <cassert> #include<functional> using namespace std; //霍夫曼数结点 class HuffManNode { friend class HuffManTree; public: HuffManNode(){} HuffManNode(int element, HuffManNode *lchild = NULL, HuffManNode *rchild = NULL); int GetWeight() const; private: int weight;//结点的权值 HuffManNode *left;//左孩子 HuffManNode *right;//右孩子 }; //函数对象 class Greater { public: bool operator() (const HuffManNode* left, const HuffManNode* right) { return left->GetWeight() > right->GetWeight(); } }; // 霍夫曼树 class HuffManTree { public: HuffManTree() { root = NULL; } void Initialize(int arr[], int n); void MakeHuffManTree(); int GetTotalWeight() const; void MiddleOrderOutPut(HuffManNode *node); HuffManNode* GetRoot() const; private: priority_queue<HuffManNode*, vector<HuffManNode*>, Greater> d; HuffManNode* root; }; int main() { int arr[] = {5, 10, 20 ,30, 30}; int n = sizeof(arr) / sizeof(int); HuffManTree tree; tree.Initialize(arr, n); tree.MakeHuffManTree(); cout<<"Total Wright = "<<tree.GetTotalWeight()<<endl; cout<<"中序输出:"; tree.MiddleOrderOutPut(tree.GetRoot()); cout<<endl; return 0; } //函数功能:构造函数 HuffManNode::HuffManNode(int element, HuffManNode *lchild, HuffManNode *rchild) { weight = element; left = lchild; right = rchild; } //函数功能:初始化 void HuffManTree::Initialize(int arr[], int n) { HuffManNode *node; for (int i=0; i<n; ++i) { node = new HuffManNode(arr[i]); d.push(node); } } //函数功能:构造霍夫曼树 void HuffManTree::MakeHuffManTree() { do { HuffManNode *min1 = d.top(); d.pop(); HuffManNode *min2 = d.top(); d.pop(); HuffManNode *sum = new HuffManNode(min1->GetWeight() + min2->GetWeight()); d.push(sum); root = sum; root->left = min1; root->right = min2; } while (d.size() > 1); } //函数功能:得到HuffManNode结点的权值 inline int HuffManNode::GetWeight() const { return weight; } //函数功能:得到树总的权值 inline int HuffManTree::GetTotalWeight() const { assert(root != NULL); return root->GetWeight(); } //函数功能:中序输出 void HuffManTree::MiddleOrderOutPut(HuffManNode *node) { HuffManNode *temp = node; if(temp != NULL) { MiddleOrderOutPut(temp->left); cout<<temp->weight<<" "; MiddleOrderOutPut(temp->right); } } //函数功能:得到树根 HuffManNode* HuffManTree::GetRoot() const { return root; } 

你可能感兴趣的:(null,Class,include)