哈夫曼树的创建
以下面的数组为例
Int [] array = {1,4,6,7,3,9}
( 1 )将各元素作为一个结点,则这些结点均只有根结点的集合,并且将数值作为各元素的权值
( 2 )先选出两个权值做小的结点创建一颗新的二叉树,并将将根结点的权值设为左右子结点的权值之和;
( 3 )然后将该二叉树放树的集合中删除原两棵根结点权值最小的树
( 4 )重复上述( 2 )和( 3 )步到集合中只剩下一棵树,则这棵树就是哈夫曼树;
在创建的过程中用到了优先队列,优先队列比较好用因为在优先队列中,元素的排序是按照自然顺序进行排列的,因此将创建好的新二叉树插入到队列后就会根据其根结点数据域的值插入到相应的位置,每次取出时均是取得的队列中最小的数据。比用普通的队列要方便很多。
package javastudy.caidan.哈夫曼0811;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Random;
/**
* 最优二叉树创建类
*
* @author
*
*/
public class MyTree {
/**
* 程序入口
*
* @param args
*/
public static void main(String args[]) {
// 优先队列
PriorityQueue<TreeNode> queue = new PriorityQueue<TreeNode>(11,
new Mycomparator());
int array[] = { 1, 4, 6, 7, 3, 9 };
// 创建一个随机数组
// Random rd = new Random();
// for (int i = 0; i < 10; i++) {
// 该随机数组中的数据在0~100中取值
// int value = rd.nextInt(100);
for (int i = 0; i < array.length; i++) {
int value = array[i];
TreeNode node = new TreeNode(value);
// 将结点对象加到队列中
queue.add(node);
}
MyTree mt = new MyTree();
mt.createTree(queue);
String code = "";
mt.print(root, code);
}
// // 判断队列中的元素是否为空
// while (queue.size() > 0) {
// // 如果不为空就从优先队列中取出一个元素
// node = queue.poll();
// 打印从队列中取出的元素
// System.out.println(node.getObj()+"\t"+node1.getObj());
// }
private static TreeNode root;
public TreeNode createTree(PriorityQueue<TreeNode> queue) {
while (queue.size() > 1) {
// 如果不为空就从优先队列中取出两个元素
TreeNode node = queue.poll();
TreeNode node1 = queue.poll();
// 取得这两个结点中的数据
Object obj = node.getObj();
Object obj1 = node1.getObj();
// 设置根结点中的数据
root = new TreeNode((Integer) obj + (Integer) obj1);
// 将根结点与原来从队列中取出的数据建立关系
root.setLeft(node);
root.setRight(node1);
node.setParent(root);
node1.setParent(root);
// 将根节点加到队列中
queue.add(root);
}
return root;
}
/**
* 遍历打印的方法
*
* @param root
*/
public void print(TreeNode root, String code) {
// if (root != null) {
// print(root.getLeft());
// Object obj = root.getObj();
// System.out.println(obj);
// print(root.getRight());
// }
if (root.getLeft() == null && root.getRight() == null) {
System.out
.println(root.getObj() + " <----> " + "的哈夫曼编码为:" + code);
}
if (root.getLeft() != null) {
print(root.getLeft(), code + '0');
}
if (root.getRight() != null) {
print(root.getRight(), code + '1');
}
}
}
// }
/**
* 创建一个比较器附属类
*
* @author 蔡丹
*
*/
class Mycomparator implements Comparator<TreeNode> {
/**
* 实现Comparator中的方法
*/
public int compare(TreeNode o1, TreeNode o2) {
return (Integer) o1.getObj() - (Integer) o2.getObj();
}
public boolean equals(Object obj) {
return false;
}
}
程序运行的结果如下
其哈弗曼编码所得原因由上图可知。