数据结构④ 树和哈夫曼树

目录

存储结构

双亲表示法

孩子链表

孩子兄弟表示法

树与二叉树转换

森林和二叉树的转换

树的遍历

哈夫曼树

基本概念

构造

原理

实现

哈夫曼编码

原理

实现

实际应用


存储结构

双亲表示法

#include<stdio.h>
#define MAXSIZE 100

typedef struct PTNode{
	int data;
	int parent;
}PTNode;

typedef struct PTree{
	PTNode nodes[MAXSIZE];
	int root , n;
}PTree;

孩子链表

#include<stdio.h>
#define MAXSIZE 100

typedef struct CTNode{
	int child;
	struct CTNode* next;
}*ChildPtr;

typedef struct{
	int data;
	CTNode* firstchild;
}CTBox;

typedef struct{
	CTBox nodes[MAXSIZE];
	int root , n;
}CTree;

优化:带双亲的孩子链表

孩子兄弟表示法

typedef struct CBNode{
	int data;
	struct CBNode *firstchild , *nextbrother;
}CBNode , *CBTree;

树与二叉树转换

 

森林和二叉树的转换

例题:

树的遍历

 

例题:

 

哈夫曼树

基本概念

 

 

 

 

构造

原理

 

实现

 

 

 

 

typedef struct{
	int weight;
	int parent , lch , rch;
}HTNode , *HuffmanTree;

void CreatHuffmanTree(HuffmanTree HT , int n){
	if(n <= 1)	return ;
	int m = 2 * n - 1;
	HT = new HTNode[m + 1];
	memset(HT , '\0' , sizeof HT);
	for(int i = 0 ; i <= n ; i++){
		int w;
		scanf("%d",&w);
		HT[i].weight = w;
	}
	for(int i = n + 1 ; i <= m ; i++){
		int s1 , s2;
		Select(HT , i - 1 , s1 , s2);
		//Select 可以用二叉堆或者每次都快排一次
		HT[s1].parent = i;
		HT[s2].parent = i;
		HT[i].lch = s1;
		HT[i].rch = s2;
		HT[i].weight = HT[s1].weight + HT[s2].weight;
		
	}
}

哈夫曼编码

原理

 

 

实现

 

typedef struct HTNode{
	int weight;
	int parent , lch , rch;
}HTNode , *HuffmanTree;

typedef char** HuffmanCode ;

void CreateHuffmanCode(HuffmanTree HT , HuffmanCode &HC , int n){
	HC = new char*[n + 1];
	char* cd = new char[n];
	cd[n - 1] = '\0';
	for(int i = 1 ; i <= n ; i++){
		int start = n - 1 ;
		int save = i;
		int p = HT[i].parent;
		while(p != 0){
			if(HT[p].lch == save){
				cd[--start] = 0;
			}else{
				cd[--start] = 1;
			}
			save = p;
			p = HT[p].parent;
		}
		HC[i] = new char[n - start];
		strcmp(HC[i] , &cd[start]);
	}
	delete cd;
}

(小蒟蒻手敲的,对伪代码进行补充,HuffmanCode 类型是按理解补的,只能保证语法无误,欢迎佬指正!) 

实际应用

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值