Repository navigation
Expand file tree
/
Copy pathHuffmanCoding.cpp
More file actions
89 lines (70 loc) · 1.62 KB
/
Copy pathHuffmanCoding.cpp
File metadata and controls
89 lines (70 loc) · 1.62 KB
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
#include<iostream>
#include<map>
#include<queue>
#include<vector>
using namespace std;
class TreeNode{
public:
char data;
int frequency;
TreeNode* left = NULL;
TreeNode* right = NULL;
TreeNode(char data, int frequency){
this->data=data;
this->frequency=frequency;
}
};
class Compare{
public:
bool operator()(TreeNode* node1, TreeNode* node2){
return node1->frequency>node2->frequency;
}
};
void getFrequencyMap(map<char, int> &freq, string s){
for(int i=0;i<s.length();i++){
freq[s[i]]++;
}
}
void printCodes(TreeNode* root, string code){
if(root==NULL)
return;
if(root->data!='$')
cout<<root->data<<" : "<<code<<endl;
printCodes(root->left, code+"0");
printCodes(root->right, code+"1");
}
void inorder(TreeNode* root){
if(root==NULL)
return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
void createHuffmanTree(map<char, int> freq){
priority_queue<TreeNode*, vector<TreeNode*>, Compare> pq;
for(auto i:freq){
pq.push(new TreeNode(i.first, i.second));
}
TreeNode* top;
TreeNode* left;
TreeNode* right;
while(pq.size() > 1){
left=pq.top();
pq.pop();
right=pq.top();
pq.pop();
top=new TreeNode('$',left->frequency+right->frequency);
top->left=left;
top->right=right;
pq.push(top);
}
TreeNode* root = pq.top();
printCodes(pq.top(),"");
}
int main(){
string s;
cin>>s;
map<char, int> freq;
getFrequencyMap(freq, s);
createHuffmanTree(freq);
}