package 哈弗曼树;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class Node{
String data;
double weight;
Node leftChild;
Node rightChild;
public Node(String data, double weight) {
super();
this.data = data;
this.weight = weight;
}
@Override
public String toString() {
return data;
}
}
public class 哈弗曼树的建立 {
static List
list = new ArrayList
();
public static void main(String[] args) {
List
nodes = new ArrayList
();
nodes.add(new Node("A",40.0));
nodes.add(new Node("B",8.0));
nodes.add(new Node("C",10.0));
nodes.add(new Node("D",30.0));
nodes.add(new Node("E",10.0));
nodes.add(new Node("F",2.0));
Node root = createTree(nodes);
list = 打印(root);
for(int i = 0 ; i < list.size() ; i++){
if(list.get(i).data!=null)
System.out.println(list.get(i).data);
}
}
private static List 打印(Node root) {
Queue queue = new LinkedList();
queue.offer(root);
while(!queue.isEmpty()){
list.add((Node)queue.peek());
Node node = (Node) queue.poll();
if(node.leftChild!=null){
queue.offer(node.leftChild);
}
if(node.rightChild!=null){
queue.offer(node.rightChild);
}
}
return list;
}
private static Node createTree(List
nodes) {//创建树 while(nodes.size()>1){ quickSort(nodes);//先进行快速排序 Node left = nodes.get(nodes.size() - 1);//取出第一小 Node right = nodes.get(nodes.size() - 2);//取出第二小 Node parent = new Node(null,left.weight + right.weight);//创建一个新节点,它的权值为left和right之和 parent.leftChild = left;//让新产生的节点的左娃娃指向left parent.rightChild = right;//让新产生的节点的右娃娃指向right nodes.remove(nodes.size() - 1);//删除左娃娃和右娃娃 nodes.remove(nodes.size() - 1); nodes.add(parent);//添加parent } return nodes.get(0);//最后返回nodes中唯一的一个节点 ,即root } private static void quickSort(List
nodes) { subSort(nodes,0,nodes.size() - 1); } private static void subSort(List
nodes, int start, int end) { if(start < end){ int i = start ; int j = end + 1; Node base = nodes.get(start); while(true){ while(i < end && nodes.get(++i).weight >= base.weight); while( j > start && nodes.get(--j).weight <= base.weight); if( i < j){ swap(nodes, i, j); }else{ break; } } swap(nodes,start,j); subSort(nodes,start ,j-1); subSort(nodes, j+1, end); } } private static void swap(List
nodes, int i, int j) { Node tmp = nodes.get(i); nodes.set(i, nodes.get(j)); nodes.set(j, tmp); } }
哈弗曼树的java实现
最新推荐文章于 2024-06-21 22:09:33 发布