public HuffmanTree(int[] weights) {
this.charset = "";
for (int i = 0; i < weights.length; i++)
this.charset += (char) ('A' + i);
int n = weights.length;
this.huftree = new TriElement[2 * n - 1];
for (int i = 0; i < n; i++)
this.huftree[i] = new TriElement(weights[i]);
for (int i = n; i < 2 * n - 1; i++) {
int min1 = Integer.MAX_VALUE, min2 = min1;
int x1 = -1, x2 = -1;
for (int j = 0; j < i; j++) {
if (this.huftree[j].parent == -1) {
if (this.huftree[j].data < min1) {
min2 = min1;
x2 = x1;
min1 = this.huftree[j].data;
x1 = j;
} else if (this.huftree[j].data < min2) {
min2 = huftree[j].data;
x2 = j;
}
}
}
this.huftree[x1].parent = i;
this.huftree[x2].parent = i;
this.huftree[i] = new TriElement(min1 + min2, -1, x1, x2);
}
}
private String getCode(int i) {
int n = 10;
char hufcode[] = new char[n];
int child = i, parent = this.huftree[child].parent;
for (i = n - 1; parent != -1; i--) {
hufcode[i] = (huftree[parent].left == child) ? '0' : '1';
child = parent;
parent = huftree[child].parent;
}
return new String(hufcode, i + 1, n - 1 - i);
}
public String toString() {
String str = "Huffman树的节点";
for (int i = 0; i < this.huftree.length; i++)
str += this.huftree[i].toString() + ",";
str += "\nHuffman编码";
for (int i = 0; i < this.charset.length(); i++) {
str += this.charset.charAt(i) + ":" + getCode(i) + ",";
}
return str;
}
public static void main(String[] args) {
String text = "abde";
int[] A = { 7, 5, 1, 2 };
HuffmanTree ht = new HuffmanTree(A);
System.out.println(ht.toString());
}
报错信息
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at shujujiegou.HuffmanTree.<init>(HuffmanTree.java:33)
at shujujiegou.HuffmanTree.main(HuffmanTree.java:67)