哈夫曼树的java实现

首先:定义哈夫曼树的节点类,为了方便使用集合类的排序功能,实现了Comparable接口(可以不是实现该接口,此时需要实现排序功能)

package my.huffmanTree;

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

然后:实现哈夫曼树的主题类,其中包括两个静态的泛型方法,为创建哈夫曼树和广度优先遍历哈夫曼树

package my.huffmanTree;

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

最后:编写一共测试端

package my.huffmanTree;

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

public class Test {
	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);
	}
}

其中添加四个节点,其权重为{7,5,4,2},最终按照广度优先遍历,应为七个节点,为:18,7,11,5,6,2,4;

控制台输出为:

[data:null;weight:18.0, data:a;weight:7.0, data:null;weight:11.0, data:b;weight:5.0, data:null;weight:6.0, data:d;weight:2.0, data:c;weight:4.0]

与实际想符合。


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