-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHuffman Encoding (GFG)
50 lines (50 loc) · 1.3 KB
/
Huffman Encoding (GFG)
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
typedef struct node {
int data;
node *left;
node *right;
node(int val) {
data = val;
left = nullptr;
right = nullptr;
}
} node;
void preorder(node *root, vector<string> &ans, string res) {
if(root -> left == nullptr && root -> right == nullptr) {
ans.push_back(res);
return;
}
preorder(root -> left, ans, res + "0");
preorder(root -> right, ans, res + "1");
}
struct comp{
bool operator()(node *f, node *s) {
return f -> data > s -> data;
}
};
vector<string> huffmanCodes(string S,vector<int> f,int N)
{
// Code here
auto comp = [](node *f, node *s) {
return f -> data > s -> data;
};
priority_queue<node*, vector<node*>, decltype(comp)> pq(comp);
//priority_queue<node*, vector<node*>, comp> pq;
for(int i = 0; i < N; i++){
pq.push(new node(f[i]));
}
while(pq.size() > 1) {
node *first = pq.top();
pq.pop();
node *second = pq.top();
pq.pop();
node *temp = new node(first -> data + second -> data);
temp -> left = first;
temp -> right = second;
pq.push(temp);
}
node *root = pq.top();
pq.pop();
vector<string> ans;
preorder(root, ans, "");
return ans;
}