首先需要借助一个堆
Heap.hpp
#pragma once
#include<iostream>
#include<vector>
#include<assert.h>
template<class T>
class Greater
{
public:
bool operator()(const T&left, const T&right) const
{
return left > right;
}
};
template<class T>
class Less
{
public:
bool operator()(const T&left, const T&right) const
{
return left < right;
}
};
template<class T, class Compare = Less<T> >
class Heap
{
public:
Heap(){}
Heap(const T* arr, size_t size)
{
assert(arr);
for (size_t i = 0; i < size; ++i)
{
_heap.push_back(arr[i]);
}
size_t root = _heap.size() / 2 - 1;
for (int i = root; i >= 0; --i)
{
_adjustDown(i);
}
}
size_t Size()
{
return _heap.size();
}
bool Empty()
{
if (_heap.size())
return 1;
return 0;
}
const T& Top()const
{
assert(_heap.size());
return _heap[0];
}
void Insert(const T&data)
{
_heap.push_back(data);
if (_heap.size() > 1)
{
size_t child = _heap.size() - 1;
_adjustUp(child);
}
}
void Print()
{
assert(!_heap.empty());
for (size_t i = 0; i < _heap.size(); ++i)
{
std::cout << _heap[i] << " ";
}
std::cout << std::endl;
}
void Pop()
{
assert(!_heap.empty());
if (_heap.size() > 1)
{
_heap[0] = _heap[_heap.size() - 1];
_heap.pop_back();
_adjustDown(0);
}
else
{
_heap.pop_back();
}
}
private:
void _adjustUp(size_t child)
{
size_t root = (child - 1) / 2;
while ((child>0) && (Compare()(_heap[child], _heap[root])))
{
std::swap(_heap[child], _heap[root]);
child = root;
root = (root - 1) / 2;
}
}
void _adjustDown(size_t root)
{
size_t child = root * 2 + 1;
while (child<_heap.size())
{
if (((child + 1)<_heap.size()) && (Compare()(_heap[child + 1], _heap[child])))
{
child = child + 1;
}
if (Compare()(_heap[child], _heap[root]))
{
std::swap(_heap[root], _heap[child]);
}
root = child;
child = child * 2 + 1;
}
}
private:
std::vector< T > _heap;
};
其次需要借助哈夫曼树 HuffmanTree.hpp
#pragma once
#include"Heap.hpp"
#include<queue>
template<class T>
class Compare
{
public:
bool operator()(T left, T right)
{
return left->_weight < right->_weight;
}
};
template<class T>
struct HuffmanTreeNode
{
HuffmanTreeNode(const T &weight)
:_weight(weight)
, pleft(NULL)
, pright(NULL)
, parent(NULL)
{}
T _weight;
HuffmanTreeNode* pleft;
HuffmanTreeNode* pright;
HuffmanT