Java实现HuffmanTree

1.结点类

package edu.tcu.soft.tree;

/*结点类*/
public class Node{

	private int weight;// 结点权值
	private Node parent;// 双亲结点
	private Node left;// 左孩子结点
	private Node right;// 右孩子结点

	public int getWeight() {
		return weight;
	}

	public void setWeight(int weight) {
		this.weight = weight;
	}

	public Node getParent() {
		return parent;
	}

	public void setParent(Node parent) {
		this.parent = parent;
	}

	public Node getLeft() {
		return left;
	}

	public void setLeft(Node left) {
		this.left = left;
	}

	public Node getRight() {
		return right;
	}

	public void setRight(Node right) {
		this.right = right;
	}

	public Node(int weight, Node parent, Node left, Node right) {
		this.weight = weight;
		this.parent = parent;
		this.left = left;
		this.right = right;
	}
	
	
	public Node(int weight) {
        this.left=null;
        this.right=null;
        this.parent=null;
		this.weight = weight;
	}

	public Node() {
		
	}

	public int compare(Node o1, Node o2) {
		return o1.getWeight() - o2.getWeight();
	}

}

2.比较器类

package edu.tcu.soft.tree;

import java.util.Comparator;

/*权值比较器*/
@SuppressWarnings("rawtypes")
public class WeightComparator implements Comparator{

	public int compare(Object o1, Object o2) {
		
        Node node1=(Node)o1;
        Node node2=(Node)o2;
		return node1.getWeight()-node2.getWeight();
	}

}


3.哈夫曼树的实现类
package edu.tcu.soft.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*哈夫曼树的实现类*/
public class HuffmanTree {

	private List list = new ArrayList();

	// 构造哈夫曼树
	@SuppressWarnings("unchecked")
	public void createTree(int a[]) {
		// 初始化结点
		Node node;
		for (int i = 0; i < a.length; i++) {
			node = new Node(a[i]);
			list.add(node);
		}
		Collections.sort(list, new WeightComparator());
		// 将list里最小的两个结点合并
		for (int n = a.length; n>1; n--) {
			node = new Node(list.get(0).getWeight() + list.get(1).getWeight(),
					null, list.get(0), list.get(1));
			list.remove(0);//移除先前index为0的结点
			list.remove(0);//移除先前index为1的结点
			list.add(node);//添加新生成的结点
			Collections.sort(list, new WeightComparator());//重新排序
		}
		node=list.get(0);//获取哈夫曼树的根结点
		System.out.println("打印所有结点");
		preOrder(node);//前序遍历哈夫曼树
	}
	
	public void preOrder(Node root) {
		 // -------------------1.递归
		 if (root == null) {
		 return;
		 } else {
		 System.out.print(root.getWeight() + " ");// 输出结点的数据域
		 preOrder(root.getLeft()); // 遍历左子树
		 preOrder(root.getRight());//遍历右子树
		 }
		}

}

总结:虽然实现了哈夫曼树,但是感觉这种实现的方法的代价很大。每一次通过两个最小的权值获得新的权值后,每一次都要重新排序。待续。。。


你可能感兴趣的:(数据结构)