Outline
Generally refers to the Huffman tree of the Huffman tree, given N weights as the N leaf nodes, a binary tree configuration, if the weighted path length of the tree reaches a minimum, such a binary tree is called optimal binary tree , and called Huffman tree (Huffman tree).
Huffman tree is the shortest path length weighted tree, the larger the weight from the root node closer.
application
1. Huffman coding (as detailed in another blog Huffman coding
Structure principle
Suppose there are n weights, the Huffman tree is constructed with n leaf nodes. n weight values are set to w1, w2, ..., construction rules wn, the Huffman tree is:
(1) w1, w2, ..., wn are n as forest trees (each tree node there is only one);
(2) selecting the root node in the forest two minimum weight tree merge as a new tree in the left and right sub-tree, and the tree is the root of its right to a new left and right subtree root sum of weights of the nodes;
(3) Delete selected two trees from the forest, and the addition of new forest tree;
(4) repeat (2), (3) step, until a forest only until the tree, the tree that is obtained by Huffman tree.
Code
Node Class
public class Node implements Comparable<Node>{
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
@Override
public int compareTo(Node o) {
// TODO Auto-generated method stub
return this.value - o.value; //整体添加负号表示从大到小排序
}
@Override
public String toString() {
//重写toString方法,只显示value值
return "Node [value=" + value + "]";
}
public int getDate() {
// TODO Auto-generated method stub
return this.value;
}
}
mian:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestHuffmanTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {3,7,8,29,5,11,23,12};
Node node = creatHuffmanTree(arr);
System.out.println(node); //打印出根结点(最小根)
}
//创建赫夫曼树
public static Node creatHuffmanTree(int[] arr) {
//使用数组中的所有元素创建若干个二叉树(只有一个结点)
List<Node> nodes = new ArrayList<>(); //创建二叉树集合
for(int value:arr) {
nodes.add(new Node(value));
}
//循环处理
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(left.getDate() + right.getDate());
parent.left = left;
parent.right = right;
//把取出来的两个二叉树移除
nodes.remove(left);
nodes.remove(right);
//将新二叉树放入原来的二叉树集合中
nodes.add(parent);
}
return nodes.get(0);
}
}