Huffman树,又称为最优二叉树,是加权路径长度最短的二叉树。
【贪心算法】是指在问题求解时,总是做出当前看起来最好的选择。也就是说贪心算法做出的不是整体最优的的选择,而是某种意义上的局部最优解。贪心算法不是对所有的问题都能得到整体最优解。
使用贪心算法构建Huffman树
template<class T>
struct HuffmanTreeNode
{
T _weight;
HuffmanTreeNode<T>* _left;
HuffmanTreeNode<T>* _right;
HuffmanTreeNode<T>* _parent;
HuffmanTreeNode(const T& x)
:_weight(x)
,_left(NULL)
,_right(NULL)
,_parent(NULL)
{}
};
template<class T>
class HuffmanTree
{
typedef HuffmanTreeNode<T> Node;
public:
HuffmanTree()
:_root(NULL)
{}
HuffmanTree(T* a,size_t size)
{
struct NodeLess
{
bool operator()(Node* l,Node* r) const
{
return l->_weight>r->_weight ;
}
};
//建小堆--》这里用到堆在我以前的博客中有
Heap<Node*,NodeLess> MinHeap;
for(size_t i=0;i<size;++i)
{
Node* node=new Node(a[i]);
MinHeap.Push (node);
}
//构树
while(MinHeap.size ()>1)
{
Node* left=MinHeap.Top ();
MinHeap.Pop ();
Node* right=MinHeap.Top ();
MinHeap.Pop ();
Node* parent=new Node(left->_weight +right->_weight );
parent->_left =left;
parent->_right =right;
left->_parent =parent;
right->_parent =parent;
MinHeap.Push (parent);
}
_root=MinHeap.Top ();
}
private:
Node* _root;
};
void TestHuffmanTree()
{
int a[]={3,2,1,4};
HuffmanTree<int> h(a,4);
}