本文实例为大家分享了哈夫曼树java代码,供大家参考,具体内容如下
包装臂;导入java.util.arraydeque; import java.util.arraylist; import java.util.collections; import java.util.list; import java java.util.queue;类节点<t>实现可比较<node <t >> {私人t数据;私人体重;私有节点<t>左;私有节点<t>右; public节点(t data,int weight){this.data = data; this.pewight =重量; } public int compareTo(node <t> other){if(this.weater> ether.getWeight()){return -1; } if(this.Wewight <其他.getWeight()){return 1; }返回0; } public t getData(){返回数据; } public void setData(t data){this.data = data; } public int getWeight(){返回重量; } public void setWeight(int weight){this.awight = stright; } public Node <t> getLeft(){返回; } public void setleft(node <t>左){this.left = left; } public node <t> getright(){返回正确; } public void setRight(node <t> right){this.right = right; } public String toString(){返回“ data:”+this.data+“; strize:”+this.pewight; }} public class huffuman <t> {static <t> node <t> create(list <node <t >> nodes){while(nodes.size()> 1){collections.sort.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(parent); }返回nodes.get(0); } static <t> list <node <t>>广度(node <t> root){list <node <t >> list = new arraylist <node <node <t >>();队列<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()); }}返回列表; } public static void main(string [] args){// todo auto-generated方法stub list <node <node <node <string >> list = new arraylist <nonode <node <node <string >>(); list.Add(新节点<String>(“ A”,7)); list.Add(新节点<String>(“ B”,5)); list.Add(新节点<String>(“ C”,4)); list.Add(新节点<String>(“ D”,2));节点<string> root = huffuman.create(list); system.out.println(huffuman.breadth(root)); // system.out.println(list); }}}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。,也希望大家多多支持武林网。