Java实现哈夫曼树的编码与解码

package demo;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

public class MyHuffman {
	 PriorityQueue<Node> nodeList = null;//节点List
	//根节点
	 Node root = null;
	 ArrayList<String> list = null;
	
	public MyHuffman() {
		 nodeList = new PriorityQueue<Node>(new Comparator<Node>() {
				public int compare(Node o1, Node o2) {
					return o1.weight-o2.weight;
				};
			});//节点List
		 root = new Node();
		 list = new  ArrayList<String>();
	}
	
	
	
	public  void creatHuffman() {
		while(nodeList.size()>1) {
			Node left = nodeList.poll();
			Node right = nodeList.poll();
			Node node = new Node( left.weight+right.weight, "", left, right);
			buquan(node);
			nodeList.add(node);
		}
		root = nodeList.poll();
	}
	public  void jiema(String str) {
		jiema(root,str);
	}
	
	public  void jiema(Node node,String str) {
		if(node.data.equals(str)){
			list.add(node.code);
		}
		if(node.lChild !=null) {
			jiema(node.lChild,str);
		}
		if(node.rChild !=null) {
			jiema(node.rChild,str);
		}
	}
	public  void buquan(Node node) {
		if(node.lChild !=null) {
			node.lChild.code = node.code+"0";
			buquan(node.lChild);
		}
		if(node.rChild !=null) {
			node.rChild.code = node.code+"1";
			buquan(node.rChild);
		}
		
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int count = Integer.valueOf(sc.nextLine());
		MyHuffman myhuffman = new  MyHuffman();
		while(count-->0) {
			String[] str = sc.nextLine().split(" ");
			Node node = new Node(str[0],Integer.valueOf(str[1]));
			myhuffman.nodeList.add(node);
		}
		myhuffman.creatHuffman();
		String input = sc.nextLine();
		for(int i=0;i<input.length();i++) {
			myhuffman.jiema(myhuffman.root,input.charAt(i)+"");
		}
		for(String out:myhuffman.list) {
			System.out.print(out);
		}
		
		
	}
	
}
class Node{
	//哈夫曼编码
	String code = "";
	//权重
	int weight;
	//数据
	String data = "";
	Node lChild;
	Node rChild;
	
	public Node() {
	}

	public Node(String data, int weight) {
		super();
		this.weight = weight;
		this.data = data;
	}

	public Node(int weight, String data, Node lChild, Node rChild) {
		super();
		this.weight = weight;
		this.data = data;
		this.lChild = lChild;
		this.rChild = rChild;
	}
	
	
}

输入 格式
位数
值 权重
字符串

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值