一个单位有12个部门,每个部门都有一部电话,但是整个单位只有一根外线,当有电话打过来的时候,由转接员转到内线电话,已知各部门使用外线电话的频率为(次/天):5 20 10 12 8 43 5 6 9 15 19 32。
利用哈夫曼树算法思想设计内线电话号码,使得接线员拨号次数尽可能少。要求:
(1)依据使用外线电话的频率构造二叉树;
(2)输出设计出的各部门内线电话号码。
//6.4 Huffman树
package huffmanTree;
public class TriElement {// 二叉树的静态三叉链表结点类
int data; // 数据域
int parent, left, right; // 父母结点和左、右孩子结点下标
// 构造结点,各参数依次指定元素、父母结点下标、左/右孩子结点下标
public TriElement(int data, int parent, int left, int right) {
this.data = data;
this.parent = parent;
this.left = left;
this.right = right;
}
public TriElement(int data) {// 构造元素值为data、无父母的叶子结点
this(data, -1, -1, -1);
}
public String toString() { // 返回结点的描述字符串
return "(" + this.data + "," + this.parent + "," + this.left + "," + this.right + ")";
}
public boolean isLeaf() {// 判断是否叶子结点
return this.left == -1 && this.right == -1;
}
}
package huffmanTree;
public class HuffmanTree1 {
private int leftNum;
private TriElement[] hufftree;
public HuffmanTree1(int[] weight) {
int n = weight.length;
this.leftNum = n;
this.hufftree = new TriElement[2 * n - 1];
for (int i = 0; i < n; i++)
this.hufftree[i] = new TriElement(weight[i]);
for (int i = 0; i < n - 1; i++) {
int min1 = Integer.MAX_VALUE, min2 = min1;
int x1 = -1, x2 = -1;
for (int j = 0; j < n + i; j++)
if (hufftree[j].data < min1 && hufftree[j].parent == -1) {
min2 = min1;
x2 = x1;
min1 = hufftree[j].data;
x1 = j;
} else if (hufftree[j].data < min2 && hufftree[j].parent == -1) {
min2 = hufftree[j].data;
x2 = j;
}
hufftree[x1].parent = n + i;
hufftree[x2].parent = n + i;
this.hufftree[n + i] = new TriElement(hufftree[x1].data + hufftree[x2].data, -1, x1, x2);
}
}
public String[] huffmanCodes() {
String[] hufcodes = new String[this.leftNum];
for (int i = 0; i < this.leftNum; i++) {
hufcodes[i] = " ";
int child = i;
int parent = hufftree[child].parent;
while (parent != -1) {
if (hufftree[parent].left == child)
hufcodes[i] = "0" + hufcodes[i];
else
hufcodes[i] = "1" + hufcodes[i];
child = parent;
parent = hufftree[child].parent;
}
}
return hufcodes;
}
}
package huffmanTree;
public class HuffmanTree_example {
public static void main(String[] args) {
int[] weight = { 5, 20, 10, 12, 8, 43, 5, 6, 9, 15, 19, 32 };
HuffmanTree1 htree = new HuffmanTree1(weight);
String[] code = htree.huffmanCodes();
System.out.println("Huffman 的编码是:");
for (int i = 0; i < code.length; i++)
System.out.println((char) ('A' + i) + ":" + code[i] + " ");
}
}