哈弗曼树
#include<iostream>
using namespace std;
//哈夫曼树的建立
struct node{
int data;
node *left;
node *right;
};
node *create(int data){
node *p = new node;
p->data = data;
p->left = NULL;
p->right = NULL;
return p;
}
//建立哈夫曼树
node *createHuffmanTree(int *a, int n){
node *p = create(a[0]);
node *q = create(a[1]);
node *root = create(p->data + q->data);
root->left = p;
root->right = q;
for(int i = 2; i < n; i++){
node *p = create(a[i]);
node *q = root;
if(p->data < q->data){
root = create(p->data + q->data);
root->left = p;
root->right = q;
}else{
while(q->right != NULL && p->data > q->right->data){
q = q->right;
}
node *r = create(p->data + q->right->data);
r->left = p;
r->right = q->right;
q->right = r;
}
}
return root;
}
//哈夫曼编码
void huffmanCode(node *root, int *a, int n){
node *p = root;
int i = 0;
while(p != NULL){
if(p->left != NULL){
a[i++] = 0;
p = p->left;
}else if(p->right != NULL){
a[i++] = 1;
p = p->right;
}else{
for(int j = 0; j < i; j++){
cout << a[j];
}
cout << endl;
while(p != NULL && p->right == NULL){
p = p->left;
i--;
}
if(p == NULL){
return;
}
p = p->right;
a[i - 1] = 1;
}
}
}