-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathHuffman Encoding.cpp
69 lines (58 loc) · 1.29 KB
/
Huffman Encoding.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
public:
struct Node
{
int data;
struct Node* left;
struct Node* right;
Node(int val)
{
data = val;
left = NULL;
right = NULL;
}
};
struct cmp
{
bool operator()(Node* l, Node* r)
{
return (l->data > r->data) ;
}
};
void preOrder(Node *root,string s, vector<string>& ans)
{
if(!root)
{
return;
}
if(!root->left && !root->right)
{
ans.push_back(s);
}
preOrder(root->left,s+"0",ans);
preOrder(root->right,s+"1",ans);
}
vector<string> huffmanCodes(string S, vector<int> f, int n )
{
priority_queue<Node*,vector<Node*>,cmp> mh;
for(int i=0; i<n; i++)
{
Node *temp = new Node(f[i]);
mh.push(temp);
}
while(mh.size() >=2)
{
Node *left = mh.top();
mh.pop();
Node *right = mh.top();
mh.pop();
Node *parent = new Node(left->data + right->data);
parent->left = left;
parent->right = right;
mh.push(parent);
}
Node *root = mh.top();
mh.pop();
vector<string> ans;
preOrder(root,"",ans);
return ans;
}