本文实例为大家分享了哈夫曼树 Java 代码 , 供大家参考 , 具体内容如下
Paketboom; Import Java.util.Arraydeque; Import Java.util.ArrayList; Import Java.util.Collections; Import Java.util.List; Import Java.util.queue; Klassenknoten <T> implementiert vergleichbar <Node <t >> {private t data; Privat int Gewicht; private Knoten <t> links; private Knoten <t> recht; öffentlicher Knoten (t data, int Gewicht) {this.data = data; this.gewicht = Gewicht; } public int vergleicheto (Knoten <T> Andere) {if (this.weight> other.getWeight ()) {return -1; } if (this.weight <other.getWeight ()) {return 1; } return 0; } public t getData () {returndaten; } public void setData (t data) {this.data = data; } public int get wweight () {return Gewicht; } public void setWeight (int Gewicht) {this.weight = Gewicht; } public node <t> getleft () {return links; } public void setleft (Knoten <t> links) {this.left = links; } public node <t> getRight () {Return Right; } public void setright (Knoten <T> rechts) {this.right = rechts; } public String toString () {return "Daten:"+this.data+"; }} public class Huffuman <T> {static <T> Knoten <T> create (list <node <t >> Knoten) {while (nodes.size ()> 1) {collections.sort (Knoten); Node <t> links = nodes.get (nodes.size ()-1); Node <t> right = nodes.get (nodes.size ()-2); Knoten <T> parent = new node <t> (null, links.getWeight ()+rechts.getWeight ()); Parent.SetRight (rechts); Parent.SetLeft (links); Knoten.Remove (links); Knoten.Remove (rechts); Knoten.Add (Elternteil); } return nodes.get (0); } static <T> list <node <t >> Breite (Knoten <T> root) {list <node <t >> list = new ArrayList <Node <t >> (); Warteschlange <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 ()); }} Rückgabeliste; } public static void main (String [] args) {// Todo automatisch generierte Methode Stubliste <Node <String >> list = new ArrayList <Node <string >> (); list.add (neuer Knoten <string> ("a", 7)); list.add (neuer Knoten <string> ("B", 5)); list.add (neuer Knoten <string> ("C", 4)); list.add (neuer Knoten <string> ("D", 2)); Knoten <string> root = huffuman.create (Liste); System.out.println (Huffuman.Breadth (root)); // system.out.println (Liste); }}以上就是本文的全部内容 , 希望对大家的学习有所帮助 , 也希望大家多多支持武林网。 也希望大家多多支持武林网。