-
Notifications
You must be signed in to change notification settings - Fork 21k
Expand file tree
/
Copy pathHuffmanCoding.java
More file actions
54 lines (43 loc) · 1.28 KB
/
HuffmanCoding.java
File metadata and controls
54 lines (43 loc) · 1.28 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
package com.thealgorithms.greedyalgorithms;
import java.util.PriorityQueue;
/**
* Huffman Coding Algorithm
*
* Greedy algorithm used for optimal prefix coding and data compression.
*
* Time Complexity: O(n log n)
* Space Complexity: O(n)
*
* https://en.wikipedia.org/wiki/Huffman_coding
*/
public class HuffmanCoding {
static class Node implements Comparable<Node> {
char character;
int frequency;
Node left;
Node right;
Node(char character, int frequency) {
this.character = character;
this.frequency = frequency;
}
@Override
public int compareTo(Node other) {
return Integer.compare(this.frequency, other.frequency);
}
}
public static Node buildHuffmanTree(char[] chars, int[] freq) {
PriorityQueue<Node> pq = new PriorityQueue<>();
for (int i = 0; i < chars.length; i++) {
pq.add(new Node(chars[i], freq[i]));
}
while (pq.size() > 1) {
Node left = pq.poll();
Node right = pq.poll();
Node parent = new Node('\0', left.frequency + right.frequency);
parent.left = left;
parent.right = right;
pq.add(parent);
}
return pq.poll();
}
}