package HuffmanTrere;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.util.ArrayList;
import java.util.Collection;
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 root=createHuffmanTree(arr);
preOrder(root);
}
public static void preOrder(Node root){
if(root!=null){
root.preOrder();
}
else {
System.out.println("是空树,不能遍历");
}
}
public static Node createHuffmanTree(int []arr){
List<Node> nodes=new ArrayList<Node>();
for(int value :arr){
nodes.add(new Node(value));
}
while (nodes.size()>1) {
//排序从小到大
Collections.sort(nodes);
System.out.println("nodes" + nodes);
//取出权值最小的数
Node leftNode = nodes.get(0);
//取出权值第二小的数
Node rightNode = nodes.get(1);
//构建一颗二叉树
Node parentNode = new Node(leftNode.value + rightNode.value);
parentNode.right = rightNode;
parentNode.left = leftNode;
//从array中删除处理过的二叉树
nodes.remove(leftNode);
nodes.remove(rightNode);
nodes.add(parentNode);
}
return nodes.get(0);
//返回赫尔曼夫的root根节点
}
}
class Node implements Comparable<Node> {
int value; //结点的权值。
Node left; //左指针
Node right; //右指针
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;
}
@Override
public String toString() {
return "Node [value=" + value + "]";
}
@Override
public int compareTo(Node o) {
return this.value - o.value; //表示从小到大排序
}
}
标签:Node,preOrder,实现,value,int,nodes,public,夫曼
From: https://www.cnblogs.com/JK8395/p/16953080.html