目录
树
存储结构
双亲表示法
#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 类型是按理解补的,只能保证语法无误,欢迎佬指正!)
实际应用