哈夫曼树---贪婪法

哈夫曼算法

第一步:初始化n个单节点的树,并为它们标上字母表中的字符。把每个字符的概率记在树的根中,用来指出树的权重(更一般地来说,树的权重等于树中所有叶子节点的概率之和)

第二步:重复下面的步骤,直到只剩一棵单独的树。找到两棵权重最小的树,把它们作为新树中的左右子树,并把其权重之和作为新的权重记录在新树的根中。

上面的算法所构造的树称之为哈夫曼树。

哈夫曼节点代码:

public class Node implements Comparable> {
	private T data;
	private double weight;
	private Node left;
	private Node right;
	
	public Node(T data, double weight){
		this.data = data;
		this.weight = weight;
	}
	
	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

	public double getWeight() {
		return weight;
	}

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

	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;
	}

	@Override
	public String toString(){
		return "data:"+this.data+";weight:"+this.weight;
	}

	@Override
	public int compareTo(Node other) {
		if(other.getWeight() > this.getWeight()){
			return 1;
		}
		if(other.getWeight() < this.getWeight()){
			return -1;
		}
		
		return 0;
	}
}


构造哈夫曼树和遍历哈夫曼树代码:

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

public class HuffmanTree {
	public static  Node createTree(List> nodes){
		while(nodes.size() > 1){
			//假如用优先队列的话,排序算法的复杂度就可以变成插入优先队列的时间复杂度logn
			Collections.sort(nodes);
			Node left = nodes.get(nodes.size()-1);
			Node right = nodes.get(nodes.size()-2);
			Node parent = new Node(null, left.getWeight()+right.getWeight());
			parent.setLeft(left);
			parent.setRight(right);
			nodes.remove(left);
			nodes.remove(right);
			nodes.add(parent);
		}
		return nodes.get(0);
	}
	
	public static  List> breadth(Node root){
		List> list = new ArrayList>();
		Queue> queue = new ArrayDeque>();
		
		if(root != null){
			queue.offer(root);
		}
		
		while(!queue.isEmpty()){
			list.add(queue.peek());
			Node node = queue.poll();
			
			if(node.getLeft() != null){
				queue.offer(node.getLeft());
			}
			
			if(node.getRight() != null){
				queue.offer(node.getRight());
			}
		}
		return list;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List> list = new ArrayList>();
		list.add(new Node("a",7));
		list.add(new Node("b",5));
		list.add(new Node("c",4));
		list.add(new Node("d",2));
		
		Node root = HuffmanTree.createTree(list);
		System.out.println(HuffmanTree.breadth(root));
//		System.out.println(list);
	}
	
}



你可能感兴趣的:(算法)