package com.monster.huffmantree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Monster
* @version v1.0
* @time 04-14-2021 22:46:01
* @description: 赫夫曼树
*/
public class HuffmanTree {
public static void main(String[] args) {
int[] arr = {13, 7, 8, 3, 29, 6, 1};
Node root = getHuffmanTree(arr);
preOrder(root);
}
public static Node getHuffmanTree(int[] arr) {
List<Node> list = new ArrayList<>();
for (int data : arr) {
list.add(new Node(data));
}
while (list.size() > 1) {
Collections.sort(list);
Node left = list.get(0);
Node right = list.get(1);
Node parent = new Node(left.value + right.value);
parent.left = left;
parent.right = right;
list.remove(left);
list.remove(right);
list.add(parent);
}
return list.get(0);
}
public static void preOrder(Node root) {
if(root != null) {
root.preOrder();
}else {
System.out.println("当前根节点为空!");
}
}
}
class Node implements Comparable<Node> {
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
@Override
public String toString() {
return "Node{" +
"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 int compareTo(Node o) {
return this.value - o.value;
}
}