-
Notifications
You must be signed in to change notification settings - Fork 0
/
HuffmanNode.java
73 lines (60 loc) · 1.98 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
64
65
66
67
68
69
70
71
72
73
// Student: Natalia Reeck Zanini
// Course: CS 211
// Assignment #10
// June 10, 2022
// This is the HuffmanNode class for Assignment #10
// Importing Libraries:
import java.io.*;
import java.util.*;
public class HuffmanNode implements Comparable<HuffmanNode> {
public static final char END_OF_FILE_CHAR = (char) 256;
// Public fields
public int frequency;
public char character;
public HuffmanNode left;
public HuffmanNode right;
// Constructs frequency of characters, and nodes that make up the HuffmanTree.
public HuffmanNode(int frequency, char character, HuffmanNode left, HuffmanNode right) {
this.frequency = frequency;
this.character = character;
this.left = left;
this.right = right;
}
public HuffmanNode(char character) {
this(-1, character, null, null);
}
public HuffmanNode(int frequency, HuffmanNode left, HuffmanNode right) {
this(frequency, ' ', left, right);
}
// Returns whether a node is a leaf node or not.
public boolean isLeaf() {
return left == null && right == null;
}
public int compareTo(HuffmanNode other) {
return frequency - other.frequency;
}
//Returns a map that counts the number of appearances for each character.
public static Map<Character, Integer> getCounts(FileInputStream input) {
Map<Character, Integer> result = new HashMap<Character, Integer> ();
try{
int curByte = input.read();
while(curByte != -1) {
char curChar = (char) curByte;
if(result.containsKey(curChar)) {
result.put(curChar, result.get(curChar) + 1);
}else{
result.put(curChar, 1);
}
curByte = input.read();
}
result.put((char) 256, 1);
return result;
}catch (IOException e) {
System.out.println("Bad File");
return null;
}
}
public String toString() {
return frequency + "," + character;
}
}