1、基本介绍
概念:
2、应用实例
package tree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class HuffmanTreeDemo {
public static void main(String[] args) {
int arr[] = {13,7,8,3,29,6,1};
Huffmantree tree = createHuffmanTree(arr);
tree.preOrderTraverse();
}
public static Huffmantree createHuffmanTree(int[] arr) {
// 1、因为要排序,所以采用List集合
List<Node> nodes = new ArrayList<>();
// 2、将数组每个元素转换为Node节点,并放入到List集合
for (int temp : arr) {
nodes.add(new Node(temp));
}
// 当List集合仅剩一个节点元素时,说明这个节点是赫夫曼树的根节点
while (nodes.size() > 1) {
// 3、对List集合元素进行升序排序
Collections.sort(nodes);
// 4、取出节点权值最小的两棵二叉树
Node node1 = nodes.get(0);
Node node2 = nodes.get(1);
// 5、组成一棵新的二叉树,新二叉树根节点的权值就是前两颗二叉树的权值之和
Node newNode = new Node(node1.weight + node2.weight);
newNode.left = node1;
newNode.right = node2;
// 6、移除取出来的两棵权值最小的二叉树
nodes.remove(node1);
nodes.remove(node2);
// 7、将新二叉树添加到List集合中进行重新排序
nodes.add(newNode);
}
return new Huffmantree(nodes.get(0));
}
}
class Huffmantree {
public Node root;
public Huffmantree(Node root) {
this.root = root;
this.root = root;
}
// 前序遍历
public void preOrderTraverse() {
if (this.root == null) {
return;
} else {
System.out.print("前序遍历:");
this.root.preOrderTraverse();
}
}
}
class Node implements Comparable<Node>{ // 对Node对象进行集合排序
public int weight;
public Node left;
public Node right;
public Node (int weight) {
this.weight = weight;
this.left = null;
this.right = null;
}
// 前序遍历
public void preOrderTraverse() {
System.out.print(this.weight + " ");
if (this.left != null) {
this.left.preOrderTraverse();
}
if (this.right != null) {
this.right.preOrderTraverse();
}
}
@Override
public int compareTo(Node o) {
// 升序排序
return this.weight - o.weight;
}
}