#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Tree{
struct Tree *left;
struct Tree *right;
int data;
}Tree;
Tree *create(int *a,int n){
Tree *tree;
Tree **b;
int i,j;
b = malloc(sizeof(Tree)*n);
for(i = 0; i < n; i++){
b[i] = malloc(sizeof(Tree));
b[i]->data = a[i];
b[i]->left = b[i]->right = NULL;
}
for(i = 1; i < n; i++){
int small1 = -1,small2;
for(j = 0; j < n; j++){
if(b[j] != NULL && small1 == -1){
small1 = j;
continue;
}
if(b[j] != NULL){
small2 = j;
break;
}
}
for(j = small2; j < n; j++){
if(b[j] != NULL){
if(b[j]->data < b[small1]->data){
small2 = small1;
small1 = j;
}
else if(b[small2]->data > b[j]->data){
small2 = j;
}
}
}
tree = malloc(sizeof(Tree));
tree->data = b[small1]->data + b[small2]->data;
tree->left = b[small1];
tree->right = b[small2];
b[small1] = tree;
b[small2] = NULL;
}
free(b);
return tree;
}
void print(Tree *tree){
if(tree){
printf("%d ",tree->data);
if(tree->left && tree->right){
printf("(");
print(tree->left);
if(tree->right)
printf(",");
print(tree->right);
printf(")");
}
}
}
int getWeight(Tree *tree,int len){
if(!tree)
return 0;
if(!tree->left && !tree->right)
return tree->data * len;
return getWeight(tree->left, len + 1) + getWeight(tree->right,len + 1);
}
void getCoding(Tree *tree,int len){
if(!tree)
return;
static int a[20];
int i;
if(!tree->left && !tree->right){
printf(" %d 的哈夫曼编码为:",tree->data);
for(i = 0; i < len; i++)
printf("%d",a[i]);
printf("\n");
}
else{
a[len] = 0;
getCoding(tree->left, len + 1);
a[len] = 1;
getCoding(tree->right, len + 1);
}
}
void Decoding(Tree *tree){
printf("请输入要解码的字符串\n");
char ch[100];
gets(ch);
int i;
int num[100];
Tree *cur;
for(i = 0; i < strlen(ch); i++){
if(ch[i] == '0')
num[i] = 0;
else
num[i] = 1;
}
if(tree){
i = 0;
while(i < strlen(ch)){
cur = tree;
while(cur->left && cur->right){
if(num[i] == 0)
cur = cur->left;
else
cur = cur->right;
i++;
}
printf("%d",cur->data);
}
}
}
int main(int argc, char *argv[]) {
int a[4] = {2,6,7,3};
Tree *tree = create(a,4);
print(tree);
printf("\n哈夫曼树的权值为:");
printf("%d\n",getWeight(tree,0));
getCoding(tree,0);
printf("解码时请参照上方编码\n");
Decoding(tree);
}