-
Notifications
You must be signed in to change notification settings - Fork 0
/
Huffman Coding.cpp
97 lines (80 loc) · 1.6 KB
/
Huffman Coding.cpp
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
#include<bits/stdc++.h>
using namespace std;
struct node{
int f;
char d;
node*left,*right;
node(int fre,char data,node*l,node*r){
f=fre;
d=data;
left=l;
right=r;
}
};
node*compare(queue<node*>&q1,queue<node*>&q2)
{
node *t=0;
if(q1.empty())
{
t=q2.front();
q2.pop();
}
else if(q2.empty()){
t=q1.front();
q1.pop();
}
else{
if(q1.front()->f < q2.front()->f)
{
t=q1.front();q1.pop();
}
else{
t=q2.front();q2.pop();
}
}
return t;
}
void print_code(node *t,int arr[],int i)
{
if(t->left)
{
arr[i]=0;
print_code(t->left,arr,i+1);
}
if(t->right)
{
arr[i]=1;
print_code(t->right,arr,i+1);
}
if(t->left==0 && t->right==0)
{
cout<<t->d<<" : ";
for(int j=0;j<i;j++)
cout<<arr[j];
//cout<<" ," ;
}
}
void build_tree(char data[],int freq[],int n )
{
queue<node*>q1,q2;
for(int i=0;i<n;i++)
{
node*t=new node(freq[i],data[i],0,0);
q1.push(t);
}
while(!q1.empty() && q1.size())
{
node *left = compare(q1,q2);
node* right =compare(q1,q2);
node* temp = new node(left->f+right->f,'$',left,right);
q2.push(temp);
}
int arr[n];
print_code(q2.front(),arr,0);
}
int main()
{
char data[]={'a','b','c','d','e','f'};
int freq[]={5,9,12,13,16,45};
build_tree(data,freq,6);
}