-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
69 lines (53 loc) · 1.33 KB
/
Copy pathsolution.js
File metadata and controls
69 lines (53 loc) · 1.33 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
class Solution {
huffmanCodes(s, f) {
class Node {
constructor(freq, idx) {
this.freq = freq;
this.idx = idx;
this.left = null;
this.right = null;
}
}
let pq = [];
// Insert all nodes into array
for (let i = 0; i < f.length; i++) {
pq.push(new Node(f[i], i));
}
// Function to sort based on frequency and index
const sortHeap = () => {
pq.sort((a, b) => {
if (a.freq === b.freq) return a.idx - b.idx;
return a.freq - b.freq;
});
};
// Special case
if (f.length === 1) return ["0"];
sortHeap();
// Build Huffman Tree
while (pq.length > 1) {
sortHeap();
let left = pq.shift();
let right = pq.shift();
let parent = new Node(
left.freq + right.freq,
Math.min(left.idx, right.idx),
);
parent.left = left;
parent.right = right;
pq.push(parent);
}
let ans = [];
const buildCodes = (root, code) => {
if (!root) return;
// Leaf node
if (!root.left && !root.right) {
ans.push(code);
return;
}
buildCodes(root.left, code + "0");
buildCodes(root.right, code + "1");
};
buildCodes(pq[0], "");
return ans;
}
}