哈夫曼树c语言实现

由于哈夫曼树是最优二叉树,所以我们只要用两个指针变量表示其孩子,一个变量表示父亲。
结构体如下

{
	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);
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值