#ifndef HuffmanTree_h
#define HuffmanTree_h
#include "HuffmanMinHeap.h"
#include "HuffmanNode.h"
template
<
class
T>
class
HuffmanTree {
public
:
HuffmanTree();
~HuffmanTree();
void
Create(T w[],
int
n);
void
Merge(HuffmanNode<T> *first, HuffmanNode<T> *second, HuffmanNode<T> *parent);
void
PreOrder();
private
:
HuffmanNode<T> *root;
void
Destroy(HuffmanNode<T> *current);
void
PreOrder(HuffmanNode<T> *current);
};
template
<
class
T>
HuffmanTree<T>::HuffmanTree() {
root = NULL;
}
template
<
class
T>
HuffmanTree<T>::~HuffmanTree() {
Destroy(root);
}
template
<
class
T>
void
HuffmanTree<T>::Destroy(HuffmanNode<T> *current) {
if
(current != NULL) {
Destroy(current->leftChild);
Destroy(current->rightChild);
delete
current;
current = NULL;
}
}
template
<
class
T>
void
HuffmanTree<T>::Create(T w[],
int
n) {
int
i;
MinHeap<T> hp;
HuffmanNode<T> *first, *second, *parent = NULL;
HuffmanNode<T>*work =
new
HuffmanNode<T>();
if
(work == NULL) {
cerr <<
"存储空间分配失败!"
<< endl;
exit
(1);
}
for
(i = 0; i < n; i++) {
work->weight = w[i];
work->leftChild = work->rightChild = work->parent = NULL;
hp.Insert(work);
}
for
(i=0; i < n-1; i++) {
first = hp.getMin();
second = hp.getMin();
parent =
new
HuffmanNode<T>();
if
(parent == NULL) {
cerr <<
"存储空间分配失败!"
<< endl;
exit
(1);
}
Merge(first, second, parent);
hp.Insert(parent);
}
root = parent;
}
template
<
class
T>
void
HuffmanTree<T>::Merge(HuffmanNode<T> *first, HuffmanNode<T> *second, HuffmanNode<T> *parent) {
parent->leftChild = first;
parent->rightChild = second;
parent->weight = first->weight + second->weight;
first->parent = second->parent = parent;
}
template
<
class
T>
void
HuffmanTree<T>::PreOrder() {
PreOrder(root);
}
template
<
class
T>
void
HuffmanTree<T>::PreOrder(HuffmanNode<T> *current) {
if
(current != NULL) {
cout << current->weight <<
" "
;
PreOrder(current->leftChild);
PreOrder(current->rightChild);
}
}
#endif /* HuffmanTree_h */