-
Notifications
You must be signed in to change notification settings - Fork 0
/
HuffmanTree.java
63 lines (55 loc) · 1.77 KB
/
HuffmanTree.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
import java.util.HashMap;
/**
* Created by Sonia on 11/28/2017.
*/
public class HuffmanTree implements Comparable <HuffmanTree> {
HuffmanNode root;
public HuffmanTree(HuffmanNode root){
this.root = root;
}
public HuffmanNode getRoot() {
return root;
}
public HuffmanTree mergeTrees(HuffmanTree right){
int weight = this.root.getWeight() + right.getRoot().getWeight();
HuffmanNode root = new HuffmanNode(weight, "???");
root.setLeftChild(this.getRoot());
root.setRightChild(right.getRoot());
return new HuffmanTree(root);
}
public int compareTo(HuffmanTree o) {
int ret = 0;
if (this.root.getWeight() < o.root.getWeight()){
ret = -1;
}
else if(this.root.getWeight() > o.root.getWeight()){
ret = 1;
}
return ret;
}
public void printAllCodes(HuffmanNode node, String code){
if(!node.getValue().equals("???")){
if(node.getValue().equals("\n")){
System.out.println("\\n " + code);
}
else if(node.getValue().equals(" ")){
System.out.println("\\s " + code);
}
else{System.out.println(node.getValue() + " " + code);}
}
else{
printAllCodes(node.getLeftChild(), code+"0");
printAllCodes(node.getRightChild(), code+"1");
}
}
public HashMap getAllCodes(HashMap <String, String> map, HuffmanNode node, String code){
if(!node.getValue().equals("???")){
map.put(node.getValue(), code);
}
else{
getAllCodes(map, node.getLeftChild(), code + "0");
getAllCodes(map, node.getRightChild(), code + "1");
}
return map;
}
}