由于哈夫曼树是最优二叉树,所以我们只要用两个指针变量表示其孩子,一个变量表示父亲。
结构体如下
{
struct hahahahahaha* father;
struct hahahahahaha* left;
struct hahahahahaha* right;
int data;
}left;
在生成小顶堆的时候,我用排序,直接塞到一个指针组的指针组里排,方便数据的新增与拿取。
left* built_tree(int* a, int n)
{
int i = 0;
left *b[205];
while (i < n)
{
left *s = creat_left();
s->data = a[i];
b[i] = s;
i++;
}
int j = 0;
while (j < 150)
{
b[i + j] = creat_left();
j++;
}
i = n / 2 -1;
sort(b, n);//sort(b,b+n)
left* s=NULL;
while (n > 1)
{
int dad =b[0]->data+b[1]->data;
s= creat_left();
s->data = dad;
b[0]->father = s;
b[1]->father = s;
s->left = b[0];
s->right = b[1];
b[0] = s;
b[1] = b[n - 1];
n--;
sort(b, n);
}
return s;
}
源代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct hahahahahaha
{
struct hahahahahaha* father;
struct hahahahahaha* left;
struct hahahahahaha* right;
int data;
}left;
void swap(left* a, left* b)
{
left t = *a;
left tt = *b;
*a = tt;
*b = t;
}
left* creat_left()
{
left* s = (left*)malloc(sizeof(left));
s->father = NULL;
s->left = NULL;
s->right = NULL;
return s;
}
typedef struct nnn1
{
struct nnn1* next;
left* data;
}link;
link* creat_link()
{
link* s = (link*)malloc(sizeof(link));
return s;
}
void sort(left* a[], int n)
{
int i = 0, j = 0,t;
left *tt;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n -1; j++)
{
if (a[j]->data >= a[j+1]->data)
{
tt = a[j], a[j] = a[j+1]; a[j+1] = tt;
}
}
}//
}
left* built_tree(int* a, int n)
{
int i = 0;
left *b[205];
while (i < n)
{
left *s = creat_left();
s->data = a[i];
b[i] = s;//printf("%d ", b[i]->data);
i++;
}
int j = 0;
while (j < 150)
{
b[i + j] = creat_left();
j++;
}
i = n / 2 -1;
sort(b, n);
//printf("%d", b[0]->data);
left* s=NULL;
while (n > 1)
{
int dad =b[0]->data+b[1]->data;
s= creat_left();
s->data = dad;
b[0]->father = s;
b[1]->father = s;
s->left = b[0];
s->right = b[1];
b[0] = s;
b[1] = b[n - 1];
n--;
sort(b, n);
}
return s;
}
void print_treef(left* root, int deep)
{
int i = 0;
while (i < deep)
{
printf("-");
i++;
}
printf("%d\n", root->data);
if (root->left != NULL)
{
print_treef(root->left, deep * 2);
}
if (root->right != NULL)
{
print_treef(root->right, deep * 2);
}
}
int main()
{
int a[10] = { 5,8,4,11,9,13 };
left* root = built_tree(a, 6);
print_treef(root, 1);
}