哈夫曼树

Huffman.h

#include "BinaryTree.h"
#include "MinHeap.h"

template<typename Type>void Huffman(Type *elements, int n, BinaryTree<Type> &tree)
{
	BinaryTree<Type> first, second;
	BinaryTree<Type> node[20];
	for(int i = 0; i < n; i++)
		node[i].m_proot = new BinTreeNode<Type>(elements[i]);
	MinHeap<BinaryTree<Type> > heap(node, n);

	for(int i = 0; i < n-1; i++)
	{
		heap.DeleteMin(first);
		heap.DeleteMin(second);

		if(first.m_proot->GetData() == second.m_proot->GetData())
			tree = *(new BinaryTree<Type>(second, first));
		else tree = *(new BinaryTree<Type>(first, second));

		heap.Insert(tree);
	}
}

Test.cpp

#include <iostream>
using namespace std;
#include "Huffman.h"

int main(){
    BinaryTree<int> tree;
    int init[10]={3,6,0,2,8,4,9,1,5,7};
    Huffman(init,10,tree);
    cout << tree;
    tree.Destroy();
    return 0;
}

你可能感兴趣的:(哈夫曼树)