package com.datastructure.tree.binaryTree;
import java.util.*;
/**
* 哈夫曼樹
*/
public class HuffmanTree {
//測試一把
public static void main(String[] args) {
int[] arr={13,7,8,3,29,6,1};
preOrder( huffmanTree(arr));
}
//前序遍歷
public static void preOrder(Node1 root){
if (root!=null){
root.preOrder();
}else {
System.out.println("空的,無法輸出");
}
}
//創建哈夫曼樹
public static Node1 huffmanTree(int[] arr){
List<Node1> list = new ArrayList<>();
for (int value:arr) {
list.add(new Node1(value));
}
while (list.size()>1){
//排序
Collections.sort(list);
//取出最小的兩個
Node1 minNode1 = list.get(0);
Node1 minNode2 = list.get(1);
//新建一個節點,它的權值等於這兩個之和
Node1 newNode = new Node1(minNode1.getValue()+minNode2.getValue());
//組成樹
newNode.setLeftNode(minNode1);
newNode.setRightNode(minNode2);
//刪除最小的兩個,將新的節點保存
list.remove(minNode1);
list.remove(minNode2);
list.add(newNode);
}
return list.get(0);
}
}
//創建哈夫曼樹的節點
class Node1 implements Comparable<Node1>{
private int value;
private Node1 leftNode;
private Node1 rightNode;
public Node1(int value){
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node1 getLeftNode() {
return leftNode;
}
public void setLeftNode(Node1 leftNode) {
this.leftNode = leftNode;
}
public Node1 getRightNode() {
return rightNode;
}
public void setRightNode(Node1 rightNode) {
this.rightNode = rightNode;
}
@Override
public String toString() {
return "Node1{" +
"value=" + value +
'}';
}
@Override
public int compareTo(Node1 o) {
return this.value - o.value;
}
//前序遍歷
public void preOrder(){
System.out.println(this);
if (this.getLeftNode()!=null){
this.getLeftNode().preOrder();
}
if (this.getRightNode()!=null){
this.getRightNode().preOrder();
}
}
}
哈夫曼樹代碼實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.