-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.py
More file actions
59 lines (45 loc) · 1.45 KB
/
Copy pathsolution.py
File metadata and controls
59 lines (45 loc) · 1.45 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
class Solution:
class Node:
def __init__(self, freq, idx):
self.freq = freq
self.idx = idx
self.left = None
self.right = None
# Custom comparison for heap
def __lt__(self, other):
if self.freq == other.freq:
return self.idx < other.idx
return self.freq < other.freq
def buildCodes(self, root, code, ans):
if not root:
return
# Leaf node
if root.left is None and root.right is None:
ans.append(code)
return
self.buildCodes(root.left, code + "0", ans)
self.buildCodes(root.right, code + "1", ans)
def huffmanCodes(self, s, f):
import heapq
heap = []
n = len(s)
# Push all characters into heap
for i in range(n):
heapq.heappush(heap, self.Node(f[i], i))
# Special case
if n == 1:
return ["0"]
# Build Huffman Tree
while len(heap) > 1:
left = heapq.heappop(heap)
right = heapq.heappop(heap)
parent = self.Node(
left.freq + right.freq,
min(left.idx, right.idx)
)
parent.left = left
parent.right = right
heapq.heappush(heap, parent)
ans = []
self.buildCodes(heap[0], "", ans)
return ans