參考自:http://blog.csdn.net/jdhanhua/article/details/6621026java
哈夫曼樹node
哈夫曼樹(霍夫曼樹)又稱爲最優樹.ide
一、路徑和路徑長度
在一棵樹中,從一個結點往下能夠達到的孩子或孫子結點之間的通路,稱爲路徑。通路中分支的數目稱爲路徑長度。若規定根結點的層數爲1,則從根結點到第L層結點的路徑長測試
二、結點的權及帶權路徑長度
若將樹中結點賦給一個有着某種含義的數值,則這個數值稱爲該結點的權。結點的帶權路徑長度爲:從根結點到該結點之間的路徑長度與該結點的權的乘積。this
三、樹的帶權路徑長度
樹的帶權路徑長度規定爲全部葉子結點的帶權路徑長度之和,記爲WPL。spa
代碼一(樹節點):.net
/** * 樹節點 * * @author pang * * @param <T> */ public class Node<T> implements Comparable<Node<T>> { private T data; private int weight; private Node<T> left; private Node<T> right; public Node(T data, int weight) { this.data = data; this.weight = weight; } @Override public String toString() { // TODO Auto-generated method stub return "data:" + this.data + ",weight:" + this.weight + "; "; } @Override public int compareTo(Node<T> o) { // TODO Auto-generated method stub if (o.weight > this.weight) { return 1; } else if (o.weight < this.weight) { return -1; } return 0; } public T getData() { return data; } public void setData(T data) { this.data = data; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public Node<T> getLeft() { return left; } public void setLeft(Node<T> left) { this.left = left; } public Node<T> getRight() { return right; } public void setRight(Node<T> right) { this.right = right; } }
代碼二(HuffmanTree):code
import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class HuffmanTree<T> { public static <T> Node<T> createTree(List<Node<T>> nodes) { while (nodes.size() > 1) { Collections.sort(nodes); Node<T> left = nodes.get(nodes.size() - 1); Node<T> right = nodes.get(nodes.size() - 2); Node<T> parent = new Node<T>(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 <T> List<Node<T>> breath(Node<T> root) { List<Node<T>> list = new ArrayList<Node<T>>(); Queue<Node<T>> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { Node<T> pNode = queue.poll(); list.add(pNode); if (pNode.getLeft() != null) { queue.add(pNode.getLeft()); } if (pNode.getRight() != null) { queue.add(pNode.getRight()); } } return list; } }
測試類:blog
import java.util.ArrayList; import java.util.List; public class HuffmanTreeTest { public static void main(String[] args) { // TODO Auto-generated method stub List<Node<String>> nodes = new ArrayList<Node<String>>(); nodes.add(new Node<String>("b", 5)); nodes.add(new Node<String>("a", 7)); nodes.add(new Node<String>("d", 2)); nodes.add(new Node<String>("c", 4)); Node<String> root = HuffmanTree.createTree(nodes); System.out.println(HuffmanTree.breath(root)); } }