-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathHuffmanEncoding.cpp
71 lines (53 loc) · 1.36 KB
/
HuffmanEncoding.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
// https://practice.geeksforgeeks.org/problems/huffman-encoding3345/1
class Node{
public:
int data;
Node* left;
Node* right;
Node(int d){
data= d;
left= NULL;
right= NULL;
}
};
class cmp{
public:
bool operator()(Node* a, Node* b){
return a->data > b->data;
}
};
class Solution
{
public:
void traverse(Node* top, vector<string>& ans, string temp){
if(top->left==NULL && top->right==NULL){
ans.push_back(temp);
return;
}
traverse(top->left, ans, temp + '0');
traverse(top->right, ans, temp + '1');
}
vector<string> huffmanCodes(string S,vector<int> f,int N)
{
priority_queue<Node*, vector<Node*>, cmp> q;
for(auto i : f){
q.push(new Node(i));
}
while(q.size()>1){
Node* a= q.top();
q.pop();
Node* b= q.top();
q.pop();
Node* s= new Node(a->data + b->data);
s->left= a;
s->right= b;
q.push(s);
}
Node* top= q.top();
q.pop();
string temp= "";
vector<string> ans;
traverse(top, ans, temp);
return ans;
}
};