-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHuffmanNode.java
63 lines (52 loc) · 1.74 KB
/
HuffmanNode.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
package huffmanish;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class HuffmanNode<T> implements Serializable {
protected int freq;
protected T value;
protected HuffmanNode<T> left, right;
public HuffmanNode(T value, int frequency) {
this.value = value;
this.freq = frequency;
this.left = null;
this.right = null;
}
public HuffmanNode(HuffmanNode<T> left, HuffmanNode<T> right) {
this.value = value;
this.freq = left.freq + right.freq;
this.left = left;
this.right = right;
}
public Map<T, String> getCodes() {
/* Finds the prefix-free codes for each character stored in the tree. */
HashMap<T, String> code = new HashMap<T, String>();
if (this.isLeaf()) {
code.put(this.value, "0");
return code;
}
StringBuilder codeBuilder = new StringBuilder();
this.fillCodes(codeBuilder, code);
return code;
}
/* Performs a depth first search, adding the prefix-free codes of each
leaf node to the HashMap. */
private void fillCodes(StringBuilder codeBuilder, Map<T, String> code) {
if (this.isLeaf()) {
code.put(this.value, codeBuilder.toString());
return;
}
codeBuilder.append('0');
this.left.fillCodes(codeBuilder, code);
codeBuilder.deleteCharAt(codeBuilder.length() - 1);
codeBuilder.append('1');
this.right.fillCodes(codeBuilder, code);
codeBuilder.deleteCharAt(codeBuilder.length() - 1);
}
public boolean isLeaf() {
return this.left == null && this.right == null;
}
public int getFrequency() {
return this.freq;
}
}