赫夫曼树:
1.最优二叉树 2.带权路径最短的树
实现思路:
- 将节点按权值大小排序(节点可放入ArrayList集合中)
- 取出(取出后删除)最前面两个节点并生成新节点(新节点权值等于两节点权值之和),同时构建新树
- 循环1-2,直到生成赫夫曼树,即当节点只剩一个时,此时该节点为赫夫曼树的根节点
代码实现:
package Tree;
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};
HuffmanNode node = creatHuffmanTree(arr);
node.preOrder();
}
/**
* 创建HuffmanTree方法
*
* @param arr 要扎转换的数组
* @return HuffmanTree最后的根节点
*/
public static HuffmanNode creatHuffmanTree(int[] arr) {
//通过数组生成节点,并将节点全部放入ArrayList中
List<HuffmanNode> list = new ArrayList();
for (int i :
arr) {
HuffmanNode node = new HuffmanNode(i);
list.add(node);
}
while (list.size() > 1) {
//进行排序
Collections.sort(list);
//取出两个最小值生成新节点并构造成树
HuffmanNode newNode = new HuffmanNode(list.get(0).getVal() + list.get(1).getVal());
newNode.setLeft(list.get(0));
newNode.setRight(list.get(1));
//移除两个最小值
list.remove(0);
list.remove(0);
//将新生成的节点将入list
list.add(newNode);
}
//当所有节点连接成赫夫曼树后,list中只存有赫夫曼树的根节点
return list.get(0);
}
}
/**
* 节点类
*/
class HuffmanNode implements Comparable<HuffmanNode> {
private int val; //权值
//左右子节点
private HuffmanNode left;
private HuffmanNode right;
public HuffmanNode(int val) {
this.val = val;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public HuffmanNode getLeft() {
return left;
}
public void setLeft(HuffmanNode left) {
this.left = left;
}
public HuffmanNode getRight() {
return right;
}
public void setRight(HuffmanNode right) {
this.right = right;
}
@Override
public int compareTo(HuffmanNode o) {
//表示升序排列
return this.val - o.val;
}
@Override
public String toString() {
return "HuffmanNode{" +
"val=" + val +
'}';
}
/**
* 前序遍历输出
*/
public void preOrder() {
System.out.println(this);
//左递归
if (this.left != null) {
this.left.preOrder();
}
//右递归
if (this.right != null) {
this.right.preOrder();
}
}
}
运用前序遍历输出,运行结果为:
HuffmanNode{val=67}
HuffmanNode{val=29}
HuffmanNode{val=38}
HuffmanNode{val=15}
HuffmanNode{val=7}
HuffmanNode{val=8}
HuffmanNode{val=23}
HuffmanNode{val=10}
HuffmanNode{val=4}
HuffmanNode{val=1}
HuffmanNode{val=3}
HuffmanNode{val=6}
HuffmanNode{val=13}
符合预期结果