Skip to content

Commit

Permalink
Add CPP code for Huffman Encoding.
Browse files Browse the repository at this point in the history
  • Loading branch information
somya2305 committed Sep 30, 2021
1 parent f7d6c4f commit 9b4eeb5
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions Trees Algorithm/HuffmanEncoding.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct tree
{
char data;
int freq;
tree* left;
tree* right;
tree(char c,int freq)
{
left=right=NULL;
this->data=c;
this->freq=freq;
}
};
void print(tree *root,string str)
{
if(root==NULL)
return;
if(root->data!='$')
cout<<root->data<<" :"<<str<<endl;
print(root->left,str+'0');
print(root->right,str+'1');
}
int main()
{
int n;
cin>>n;
char a[n];
for(int i=0;i<n;i++)
cin>>a[i];
int f[n];
for(int i=0;i<n;i++)
cin>>f[i];
priority_queue<pair<int,tree*>,vector<pair<int,tree*>>,greater<pair<int,tree*>>>p;
for(int i=0;i<n;i++)
p.push(make_pair(f[i],new tree(a[i],f[i])));
tree *left,*right;
while(p.size()!=1)
{
left=(p.top()).second;
p.pop();
right=(p.top()).second;
p.pop();
tree* aux =new tree('$',left->freq+right->freq);
aux->left=left;
aux->right=right;
p.push(make_pair(left->freq+right->freq,aux));
}
cout<<"Huffman Codes are->"<<endl;
tree *res=(p.top()).second;
print(res,"");
return 0;
}

0 comments on commit 9b4eeb5

Please sign in to comment.