package cn.mrlij.tree;
import java.util.ArrayList;
import java.util.Arrays;
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 huffman = createHuffman(arr);
preOrder(huffman);
}
public static void preOrder(Node root){
if(root!=null){
root.preOrder();
}else {
System.out.println("树为空!");
}
}
public static Node createHuffman(int[] arr){
List<Node> nodes = new ArrayList<>();
//依次创建树
for(int val : arr){
nodes.add(new Node(val));
}
while(nodes.size()>1){
//将集合中的树的val进行排序
Collections.sort(nodes);
//取出第一个,和第二个并创建树
Node left = nodes.get(0);
Node right = nodes.get(1);
//创建树
Node parent = new Node(left.value + right.value);
parent.left = left;
parent.right = right;
//移除原先的两个数
nodes.remove(left);
nodes.remove(right);
//将新生成的树加到集合中
nodes.add(parent);
}
return nodes.get(0);
}
}
//创建树
class Node implements Comparable<Node>{
int value;
Node left;
Node right;
public Node(int value){
this.value = value;
}
//前序遍历
public void preOrder(){
System.out.println(this);
if(this.left !=null){
this.left.preOrder();
}
if(this.right!=null){
this.right.preOrder();
}
}
@Override
public String toString() {
return "Node{" +
"value=" + value +
'}';
}
@Override
public int compareTo(Node o) {
return this.value - o.value;
}
}