#pragma once
#include "Heap.h"//heap implemented using blogs
Template<class t>
Structure information of struct huffmannode//node
{
T _weight;
huffmannode<t>* _parent;
huffmannode<t>* _left;
huffmannode<t>* _right;
Huffmannode (const t& weight)
: _weight (weight)
, _parent (NULL)
, _left (NULL)
, _right (NULL)
{}
};
Template<class t>
Implementation of Class Huffmantree//huffman tree
{
typedef huffmannode<t> Node;
Public
Huffmantree ()
: _root (NULL)
{}
~huffmantree ()
{
_destroy (_root);
_root = NULL;
}
node* Getrootnode ()
{
return _root;
}
void Createhuffmantree (const t* Array, size_t size, const t& Invalid)
{
ASSERT (array && size > 0);
struct Compare
{
BOOL Operator () (node*& L, node*& R)
{
Return (L->_weight < r->_weight);
}
};
Heap<node*,compare> minheap (array, size);
heap<node*, compare> minheap;
for (size_t i = 0; i < size; ++i)
{
if (array[i]! = invalid)
{
node* node = new node (array[i]);
Minheap.push (node);
}
}
if (Minheap.empty ())
Return
node* parent = Minheap.gettop ();
while (Minheap.size () > 1)
{
node* first = Minheap.gettop ();
Minheap.pop ();
node* second = Minheap.gettop ();
Minheap.pop ();
Parent = new Node (first->_weight+second->_weight);
Parent->_left = First;
Parent->_right = second;
Minheap.push (parent);
}
_root = parent;
}
void Levelorder ()
{
Queue<node*> Q;
if (_root = = NULL)
Return
Q.push (_root);
while (!q.empty ())
{
node* cur = q.front ();
Q.pop ();
cout << cur->_weight << "";
if (cur->_left)
Q.push (Cur->_left);
if (cur->_right)
Q.push (Cur->_right);
}
}
Private
void _destroy (node*& root)
{
if (root = = NULL)
Return
_destroy (Root->_left);
_destroy (Root->_right);
Delete root;
root = NULL;
}
Protected
node* _root;
};
void Testtree ()
{
int ar[] = {2, 3, 6, 0, 4, 5, 1, 9, 7, 8};
int ar[] = {1,1,1,1,2,2};
Huffmantree<int> Tree;
Tree. Createhuffmantree (AR, sizeof (AR)/sizeof (ar[0]),-1);
Tree. Levelorder ();
}
This article is from the "end-of-the-guest" blog, please be sure to keep this source http://zheng2048.blog.51cto.com/10612048/1825214
Data structure C + + uses minimum heap to implement Huffman tree