参考https://baijiahao.baidu.com/s?id=1663514710675419737&wfr=spider&for=pc
package HuffmanTree;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CreateHuffmanTree {
public static void main(String[] args) {
int[] arr = {3, 4, 5, 76, 2, 1, 3, 4, 6, 7, 2};
Node huffmanTree = createHuffmanTree(arr);
preOrder(huffmanTree);
}
public static Node createHuffmanTree(int arr[]){
//创建list,方便操作
List<Node> nodes = new ArrayList<>();
for(int i = 0; i < arr.length; i++) {
nodes.add(new Node(arr[i]));
}
while(nodes.size() > 1){
Collections.sort(nodes);
Node leftNode = nodes.get(0);
nodes.remove(0);
Node rightNode = nodes.get(0);
nodes.remove(0);
Node parent = new Node(leftNode.weigh + rightNode.weigh);
parent.left = leftNode;
parent.right = rightNode;
nodes.add(parent);
}
Node root = nodes.get(0);
return root;
}
public static void preOrder(Node root) {
if(root == null){
return;
}
if(root.left != null) {
preOrder(root.left);
}
System.out.print("----" + root.weigh);
if(root.right != null) {
preOrder(root.right);
}
}
}
class Node implements Comparable<Node> {
public int weigh;
public Node left;
public Node right;
public Node(int weigh) {
this.weigh = weigh;
}
@Override
public int compareTo(Node o) {
return this.weigh - o.weigh;
}
}