赫夫曼树的知识和代码实现
1什么是赫夫曼树
给定n个权值作为n个叶子节点,构造成一棵二叉树,若树的带权路径长度最小(wpl)则称此树为最优二叉树。即赫夫曼树。
2创建赫夫曼树的步骤
给定一个无序的数组,进行赫夫曼树的创建步骤
-
先将数组从小到大进行排序。 -
取出根节点权值最小的两个树 -
组成一颗新的树,该新的二叉树的根节点的权值是前面两颗二叉树根节点权值的和 -
再将这两颗新的二叉树,以根节点的权值大小再次排序, -
重复步骤2
即可得到一颗赫夫曼树!(wpl值最小的树)
3赫夫曼树的代码实现
package com.njupt.binaryTree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class HuffmanTree {
public static void main(String[] args) {
int[] arr = {13, 7, 8, 3, 29, 6, 1};
NodePoint1 root = creatTree(arr);
preOrder(root);
}
public static void preOrder(NodePoint1 root) {
if (root != null) {
root.preOrder();
} else {
System.out.println("此树为空");
}
}
public static NodePoint1 creatTree(int[] arr) {
List<NodePoint1> nodePoints = new ArrayList<NodePoint1>();
for (int i = 0; i < arr.length; i++) {
nodePoints.add(new NodePoint1(arr[i]));
}
while (nodePoints.size() > 1) {
Collections.sort(nodePoints);
NodePoint1 left = nodePoints.get(0);
NodePoint1 right = nodePoints.get(1);
NodePoint1 parent = new NodePoint1(left.no + right.no);
parent.left = left;
parent.right = right;
nodePoints.remove(left);
nodePoints.remove(right);
nodePoints.add(parent);
}
return nodePoints.get(0);
}
}
class NodePoint1 implements Comparable<NodePoint1> {
int no;
NodePoint1 left;
NodePoint1 right;
public NodePoint1(int no) {
this.no = no;
}
@Override
public String toString() {
return "NodePoint1{" +
"no=" + no +
'}';
}
@Override
public int compareTo(NodePoint1 node) {
return this.no - node.no;
}
public void preOrder() {
System.out.println(this.no);
if (this.left != null) {
this.left.preOrder();
}
if (this.right != null) {
this.right.preOrder();
}
}
}
测试结果;对创建好的哈夫曼树进行前序遍历。
24
9
4
5
2
3
15
Process finished with exit code 0
|