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<Node> list = new ArrayList<Node>();

	// 構造哈夫曼樹
	@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());//遍歷右子樹
		 }
		}

}

總結:雖然實現了哈夫曼樹,但是感覺這種實現的方法的代價很大。每一次通過兩個最小的權值獲得新的權值後,每一次都要重新排序。待續。。。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章