wpl最小的就是赫夫曼树(所有叶子节点的带权路径长度之和最小)
写出来两个节点连接,然后循环就可以了
package tree.huffmantree;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};Node huffmanTree = createHuffmanTree(arr);//测试(前序遍历)preOrder(huffmanTree);}//编写一个前序遍历的方法public static void preOrder(Node root){if (root != null){root.preOrder();}else{System.out.println("空树");}}//创建赫夫曼树public static Node createHuffmanTree(int arr []){//第一步为了操作方便//1.遍历arr数组//2.将arr的每个元素构建成一个Node//3.将node放入到ArrayList中List<Node> nodes = new ArrayList<>();for(int value : arr){nodes.add(new Node(value));}//排序 从小到大while (nodes.size() > 1) {Collections.sort(nodes);//取出根节点权值最小的两颗二叉树//(1)取出权值最小的节点(二叉树)Node leftNode = nodes.get(0);//(2)取出第二小的节点Node rightNode = nodes.get(1);//(3)构建新的二叉树Node parent = new Node(leftNode.value + rightNode.value);parent.left = leftNode;parent.right = rightNode;//(4)删除掉取出的两个nodes.remove(leftNode);nodes.remove(rightNode);//(5)将parent加入到nodesnodes.add(parent);}//最后返回root节点return nodes.get(0);}
}
//创建节点类
//为了让node对象,支持排序,需要实现comparable接口
class Node implements Comparable<Node>{int value; //权值Node left; //左子节点Node right; //右子节点@Overridepublic int compareTo(Node o) {//从小到大排序return this.value - o.value;}public void preOrder(){System.out.println(this);if (this.left != null){this.left.preOrder();}if (this.right != null){this.right.preOrder();}}public Node(int value){this.value = value;}@Overridepublic String toString() {return "Node{" +"value=" + value +'}';}
}
结果: