-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhuffman_code.java
55 lines (49 loc) · 1.3 KB
/
huffman_code.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
import java.util.ArrayList;
/**
*
* @author veeki.yadav
*/
public class huffman_code {
Node t = new Node();
public ArrayList<Integer> str = new ArrayList<>();
/**
* build a huffman tree
*
* @param freq
* @return
*/
public Node huffmanTree(int[] freq, priority_queue pq) {
// merging two small tree
for (int i = 0; i < freq.length - 1; i++) {
Node left = pq.poll();
//System.out.println("Node 1 removes : " + left.freq );
Node right = pq.poll();
//System.out.println("Node 2 removes : " + right.freq );
pq.add(left.freq + right.freq, 0, left, right);
}
return pq.poll();
}
/**
*
* @param node
* @param s
*/
public void bitcode(Node node, String s) {
if (node != null) {
if (!t.isLeaf(node)) {
if (node.left != null) {
bitcode(node.left, s + "0");
}
if (node.right != null) {
bitcode(node.right, s + "1");
}
} else {
if (node.freq != 0) {
str.add(node.freq * s.length());
} else {
str.add(s.length());
}
}
}
}
}