Skip to content

Commit d59d979

Browse files
committed
Adding huffman encoding
1 parent b1784c2 commit d59d979

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
//leaf node contains character(data), intermediate nodes contains frequency
5+
struct node
6+
{
7+
struct node *l;
8+
struct node *r;
9+
char data;
10+
int freq;
11+
};
12+
13+
struct compare{
14+
bool operator()(struct node *n1,struct node *n2)
15+
{
16+
return n1->freq>n2->freq;
17+
}
18+
};
19+
20+
void traverse(node *root,string str)
21+
{
22+
if(!root)
23+
return ;
24+
25+
if(root->data!='#'){
26+
cout<<str<<" ";
27+
return;}
28+
29+
//append 0 if traverse to left branch of the node otherwise append 1
30+
31+
// if(root->l)
32+
traverse(root->l,str+"0");
33+
//if(root->r)
34+
traverse(root->r,str+"1");
35+
}
36+
int main() {
37+
//code
38+
39+
int t; //for number of test cases
40+
cin>>t;
41+
while(t--)
42+
{
43+
string s;
44+
cin>>s;
45+
priority_queue<node*,vector<node*>,compare> pq;//minheap;
46+
47+
48+
int x;
49+
for(int i=0;i<s.length();i++)
50+
{
51+
struct node *nn=(struct node *)malloc(sizeof(struct node));
52+
cin>>x;
53+
nn->freq=x;
54+
nn->data=s[i];
55+
nn->l=nn->r=NULL;
56+
pq.push(nn);
57+
}
58+
59+
while(pq.size()!=1)
60+
{
61+
struct node *left=pq.top();
62+
pq.pop();
63+
64+
struct node *right=pq.top();
65+
pq.pop();
66+
67+
node *heapNode=(node*)malloc(sizeof(node));
68+
heapNode->data='#'; // '#'' acts as character in intermediate nodes
69+
heapNode->freq=left->freq+right->freq;
70+
heapNode->l=left;
71+
heapNode->r=right;
72+
73+
pq.push(heapNode);
74+
}
75+
76+
struct node *root=pq.top();
77+
string ans="";
78+
traverse(root,ans);
79+
cout<<endl;
80+
81+
}
82+
return 0;
83+
}

0 commit comments

Comments
 (0)