This example for you to share the Huffman tree Java code for your reference, the specific contents are as follows
Package boom;
Import Java.util.ArrayDeque;
Import java.util.ArrayList;
Import java.util.Collections;
Import java.util.List;
Import Java.util.Queue;
Class Node<t> implements comparable<node<t>>{private T data;
private int weight;
Private node<t> left;
Private node<t> right;
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;
The 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) {Whil
E (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 (right);
Parent.setleft (left);
Nodes.remove (left);
Nodes.remove (right);
Nodes.Add (parent);
Return Nodes.get (0); } static<t> list<node<t>> breadth (node<t> root) {list<node<t>> List = new ArrayL
Ist<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-generated method stub list<node<string>> L
ist = 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);
}
}
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.