-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHuffmanTree.h
108 lines (86 loc) · 1.87 KB
/
HuffmanTree.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
This file define the huffman tree, and nodes, used to create the encoding to compress the data;
*/
#ifndef HUFFMAN_TREE_H
#define HUFFMAN_TREE_H
#include <algorithm>
using namespace std;
//Class Node, for internals and leaves nodes
class Node{
public:
Node *l,*r,*p;
unsigned char *data;
unsigned int v;
Node(unsigned int v){
l=r=p=NULL;
data=NULL;
this->v=v;
}
};
class HuffmanTree{
private:
//root of the tree
Node* root;
void printEncodingHelp(Node* n, int level, char* str){
#ifdef DEBUG
if(n->l==NULL && n->r==NULL){
str[level]='\x00';
printf("%s->%c = %d value\n",str,*(n->data),(unsigned int)*(n->data) );
bits_needed[*(n->data)]=level;
}
else{
if(n->l!=NULL){
str[level]='0';
printEncodingHelp(n->l,level+1,str);
}
if(n->r!=NULL){
str[level]='1';
printEncodingHelp(n->r,level+1,str);
}
}
#endif
}
int depthHelp(Node* n, int max_val){
int l=max_val,r=max_val;
if(n->l!=NULL) l=depthHelp(n->l,max_val+1);
if(n->r!=NULL) r=depthHelp(n->r,max_val+1);
return max(l,r);
}
void inOrderVisitHelp(Node* n){
#ifdef DEBUG
if(n==NULL) return;
inOrderVisitHelp(n->l);
printf("%d\n",n->v );
inOrderVisitHelp(n->r);
#endif
}
public:
//Array that contains for each symbol how many bits are needed to encode it
int bits_needed[256];
//Constructor
HuffmanTree(){
root=NULL;
for(int i=0;i<256;i++){
bits_needed[i]=0;
}
}
//Constructor overload
HuffmanTree(Node* root){
this->root=root;
}
//Function that print for each symbol its encoding
void printEncoding(){
char* str=new char[depth()+1];
printEncodingHelp(root,0,str);
delete str;
}
//Calculate the depth of the tree
int depth(){
return depthHelp(root,0);
}
//Make an in order visit
void inOrderVisit(){
inOrderVisitHelp(root);
}
};
#endif