本文实例为大家分享了哈夫曼树 Java 代码 , 供大家参考 , 具体内容如下
Boom de forfait; import java.util.arraydeque; import java.util.arraylist; import java.util.collections; import java.util.list; import java.util.queue; Class Node <T> implémente comparable <nœud <T>> {Données P privé; poids int privé; Node privé <T> gauche; Node privé <T> à droite; Node public (T data, int poids) {this.data = data; this.weight = poids; } public int compareto (node <t> autre) {if (this.weight> autre.getweight ()) {return -1; } if (this.weight <autres.getweight ()) {return 1; } return 0; } public t getData () {return data; } public void setData (t data) {this.data = data; } public int getweight () {return poids; } public void setweight (int Weight) {this.weight = poids; } Node public <T> Getleft () {return à gauche; } public void SetLeft (Node <T> Left) {this.left = Left; } Node public <T> GetRight () {return reight; } public void setRight (node <t> droit) {this.Right = droite; } public String toString () {return "data:" + this.data + "; poids:" + this.weight; }} classe publique Huffuman <T> {static <t> nœud <t> create (list <node <t>> nœuds) {while (nœuds.size ()> 1) {collection.sort (nœuds); Node <T> Left = NODES.GET (NODES.SIZE () - 1); Node <T> droite = nœuds.get (nœuds.size () - 2); Node <T> parent = new node <T> (null, Left.getweight () + droite.getWeight ()); parent.setRight (à droite); parent.setLeft (à gauche); NODES.REMOVE (à gauche); NODES.REMOVE (à droite); nœuds.add (parent); } return nœuds.get (0); } statique <T> list <node <t>> largeur (nœud <t> root) {list <node <T>> list = new ArrayList <Node <T>> (); File d'attente <nœud <t>> file d'attente = new ArrayDeque <Node <T>> (); queue.offer (racine); 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 ()); }} Retour List; } public static void main (String [] args) {// TODO Méthode générée automatique Stub list <node <string >> list = new ArrayList <Node <string>> (); list.add (nouveau nœud <string> ("a", 7)); list.add (nouveau nœud <string> ("b", 5)); list.add (nouveau nœud <string> ("c", 4)); list.add (nouveau nœud <string> ("d", 2)); Node <string> root = heffuman.create (list); System.out.println (Huffuman.Breadth (root)); // System.out.println (liste); }}以上就是本文的全部内容 , 希望对大家的学习有所帮助 , 也希望大家多多支持武林网。