-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathHuffmanCoding.java
67 lines (58 loc) · 1.76 KB
/
HuffmanCoding.java
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
/*https://practice.geeksforgeeks.org/problems/huffman-encoding3345/1/*/
class Node implements Comparable<Node> {
Node left;
char ch;
int freq;
Node right;
Node(char ch, int freq) {
super();
this.ch = ch;
this.freq = freq;
}
@Override
public String toString() {
return "";
}
@Override
public int compareTo(Node node) {
if (this.freq < node.freq) return -1;
return 1;
}
}
class Solution {
ArrayList<String> list;
public ArrayList<String> huffmanCodes(String S, int f[], int N)
{
list = new ArrayList<String>();
//add all the nodes to priority queue
PriorityQueue<Node> pq = new PriorityQueue<Node>();
for (int i = 0; i < N; ++i)
pq.add(new Node(S.charAt(i),f[i]));
//till the minheap has more than one elements
while (pq.size() > 1)
{
//poll the children
Node leftChild = pq.poll();
Node rightChild = pq.poll();
//build their parent node and attach them
Node parentNode = new Node('\0',leftChild.freq+rightChild.freq);
parentNode.left = leftChild;
parentNode.right = rightChild;
//add the parent to the minheap
pq.add(parentNode);
}
//traverse preorder and store into the final list
Node treeRoot = pq.poll();
traversePreOrder(treeRoot,"");
return list;
}
public void traversePreOrder(Node root, String currCode)
{
if (root != null)
{
if (root.ch != '\0') list.add(currCode);
traversePreOrder(root.left,currCode+"0");
traversePreOrder(root.right,currCode+"1");
}
}
}