哈弗曼树研究(JAVA)

哈弗曼编码用于数据通信的二进制编码中。我们知道设计不等长的编码,要求对字符集中的任一字符的编码都不是另一个字符编码的前缀,这样做的好处是:在进行译码的时候不需要在字符之间添加分隔符。其他的用处有:apache负载均衡的按权重请求策略的底层算法、咱们生活中的路由器的路由算法、利用哈夫曼树实现汉字点阵字形的压缩存储、快速检索信息等等底层优化算法,其实核心就是因为目标带有权重、长度远近这类信息才能构建哈夫曼树模型。

首先我们构建一个节点类:Node.java

package HuffmanTree;

public class Node {

	private String data;
	private int powder;
	private Node leftNode;
	private Node rightNode;
	
	Node(String data,int powder){
		this.data = data ;
		this.powder = powder;
	}
	
	public String toString(){
		return "[节点名:"+this.data+"  权重:"+this.powder+"]";
	}

    public int getPowder(){
    	return this.powder;
    }
    
    public Node getLeftNode(){
    	return this.leftNode;
    }
    
    public void setLeftNode(Node left){
    	this.leftNode = left ;
    }
    
    public Node getRightNode(){
    	return this.rightNode;
    }
    
    public void setRightNode(Node right){
    	this.rightNode = right ;
    }
    
	public boolean compareTo(Node node){
		return this.powder > node.powder;
	}
}

然后构建哈弗曼树:HuffmanTree.java

package HuffmanTree;

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

public class HuffmanTree {

	public static void main(String[] args) {
		Node node1 = new Node("Java",100);
		Node node2 = new Node("C",90);
		Node node3 = new Node("c#",70);
		Node node4 = new Node("javascript",50);
		List<Node> list = new ArrayList<Node>();
		list.add(node1);
		list.add(node2);
		list.add(node3);
		list.add(node4);
		Node root = crateHuffman(list);
		System.out.println(deepFirst(root));
	}
	
	public static void sort(List<Node> list){
		int len = list.size();
		for(int i=0;i<len;i++)
			for(int j=i+1;j<len;j++)
				if(list.get(i).compareTo(list.get(j))){
					Node node = list.get(i);         // 交换数组中的元素位置  
                    list.set(i, list.get(j));  
                    list.set(j, node);  
				}
	}
	
	 public static List<Node> deepFirst(Node root) {              //进行遍历输出 
	        List<Node> list = new ArrayList<Node>();  
	        Queue<Node> queue = new ArrayDeque<Node>();  
	        queue.add(root);  
	        while (!queue.isEmpty()) {  
	            list.add(queue.peek());  
	            Node twoLinkNode = queue.poll();  
	            if (twoLinkNode.getLeftNode() != null) {  
	                queue.add(twoLinkNode.getLeftNode());  
	            }  
	            if (twoLinkNode.getRightNode() != null) {  
	                queue.add(twoLinkNode.getRightNode());  
	            }  
	        }  
	        return list;  
	    }  
	
	public static Node crateHuffman(List<Node> list){
        while(list.size()>1){
        	sort(list);
        	Node left = list.get(0);
        	Node right = list.get(1);
        	Node parent = new Node("父节点", left.getPowder() + right.getPowder());
        	parent.setLeftNode(left);
        	parent.setRightNode(right);
        	list.remove(0);
        	list.remove(0);
        	list.add(parent);
        }
		return list.get(0); 
	}
}



你可能感兴趣的:(哈弗曼树研究(JAVA))