本文实例为大家分享了哈夫曼树java代码、供大家参考、具体内容如下
パッケージブーム; Import java.util.arraydeque; Import java.util.arraylist; import java.util.collections; import java.util.list; import java.util.queue;クラスノード<t>は、比較可能な<node <t >> {private t data;を実装しています。プライベートINT重量;プライベートノード<t>左;プライベートノード<t>右; public node(t data、int weight){this.data = data; this.weight = weight; } public int compareto(node <t> other){if(this.weight> other.getWeight()){return -1; } if(this.weight <other.getweight()){return 1; } return 0; } public t getData(){return data; } public void setData(t data){this.data = data; } public int getWeight(){return weight; } public void setweight(int weight){this.weight = weight; } public node <t> getLeft(){return Left; } public void setLeft(node <t> left){this.left = left; } public node <t> getRight(){return right; } public void setright(node <t> right){this.right = right; } public String toString(){return "data:"+this.data+"; weight:"+this.weight; }} public class huffuman <t> {static <t> node <t> create(list <node <t >> nodes){while(nodes.size()> 1){collections.sort(nodes); node <t> left = nodes.get(nodes.size() - 1); node <t> right = nodes.get(nodes.size() - 2); node <t> parent = new node <t>(null、left.getweight()+right.getWeight()); parent.setright(右); parent.setLeft(左); nodes.remove(左); nodes.remove(右); nodes.add(親); } nodes.get(0)を返します。 } static <t> list <node <t >> bredth(node <t> root){list <node <t >> list = new arraylist <node <t >>(); queue <node <t >> queue = new arraydeque <node <t >>(); queue.offer(root); while(queue.size()> 0){node <t> out = queue.poll(); list.add(out); if(out.getLeft()!= null){queue.offer(out.getLeft()); } if(out.getright()!= null){queue.offer(out.getright()); }} return list; } public static void main(string [] args){// todo auto-eneratedメソッドスタブリスト<node <string >> list = new arraylist <node <string >>(); list.add(new node <string>( "a"、7)); list.add(new node <string>( "b"、5)); list.add(new node <string>( "c"、4)); list.add(new node <string>( "d"、2)); node <string> root = huffuman.create(list); system.out.println(huffuman.breadth(root)); // system.out.println(list); }}以上就是本文的全部内容、希望对大家的学习有所帮助、也希望大家多多支持武林网。