-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
88 lines (71 loc) · 1.93 KB
/
Copy pathsolution.cpp
File metadata and controls
88 lines (71 loc) · 1.93 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
class Solution
{
public:
struct Node
{
int freq; // Frequency of character/subtree
int idx; // Original index to handle tie cases
Node *left;
Node *right;
Node(int f, int i)
{
freq = f;
idx = i;
left = right = NULL;
}
};
struct Compare
{
bool operator()(Node *a, Node *b)
{
// Smaller frequency should come first
if (a->freq == b->freq)
return a->idx > b->idx;
return a->freq > b->freq;
}
};
// DFS traversal to generate Huffman codes
void buildCodes(Node *root, string code, vector<string> &ans)
{
if (!root)
return;
// Leaf node
if (!root->left && !root->right)
{
ans.push_back(code);
return;
}
buildCodes(root->left, code + "0", ans);
buildCodes(root->right, code + "1", ans);
}
vector<string> huffmanCodes(string &s, vector<int> f)
{
priority_queue<Node *, vector<Node *>, Compare> pq;
int n = s.size();
// Create a node for every character
for (int i = 0; i < n; i++)
{
pq.push(new Node(f[i], i));
}
// Special case: only one character
if (n == 1)
return {"0"};
// Build Huffman Tree
while (pq.size() > 1)
{
Node *left = pq.top();
pq.pop();
Node *right = pq.top();
pq.pop();
Node *parent = new Node(
left->freq + right->freq,
min(left->idx, right->idx));
parent->left = left;
parent->right = right;
pq.push(parent);
}
vector<string> ans;
buildCodes(pq.top(), "", ans);
return ans;
}
};