哈夫曼树算法思想

一个单位有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] + " ");

	}

}

结果如下:

在这里插入图片描述

  • 10
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值