本文实例为大家分享了哈夫曼树 Java 代码 供大家参考 , 具体内容如下
упаковка бум; Import java.util.arraydeque; импорт java.util.arraylist; импорт java.util.collections; импорт java.util.list; import java.util.queue; Узел класса <t> реализует сопоставимый <узлы <t >> {private t data; частный вес; частный узел <T> остался; частный узел <T> правильно; public node (t data, int вес) {this.data = data; this.weight = вес; } public int compareto (node <t> ore) {if (this.weight> orethe.getweight ()) {return -1; } if (this.weight <ish.getweight ()) {return 1; } return 0; } public t getData () {return data; } public void setData (t data) {this.data = data; } public int get -Weuess () {return Weight; } public void легкий вес (int Weew) {this.weight = Weew; } public node <t> getleft () {return Left; } public void setleft (node <t> слева) {this.left = Left; } public node <t> getright () {return right; } public void setright (node <t> справа) {this.right = right; } public String toString () {return "data:"+this.data+"; вес:"+this.weight; }} открытый класс huffuman <t> {static <t> node <t> create (list <node <t >> узлы) {while (nodes.size ()> 1) {collectss.sort (nodes); Узел <T> левый = nodes.get (nodes.size ()-1); Узел <T> right = nodes.get (nodes.size ()-2); Node <t> parent = new Node <t> (null, left.getweight ()+right.getweight ()); parent.setright (справа); parent.setleft (слева); узлы. Remove (слева); узлы. Remove (справа); nodes.add (родитель); } return nodes.get (0); } static <t> list <node <t >> ширина (node <t> root) {list <node <t >> list = new ArrayList <node <t >> (); Очередь <узел <t >> queue = new Arraydeque <node <t >> (); queue.ffer (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 автоматическое сгенерированное метод списка <node <string >> list = new ArrayList <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 (список); }}以上就是本文的全部内容 , 希望对大家的学习有所帮助 也希望大家多多支持武林网。