Use Java to create Huffman tree code as follows:
Note All in the code said, the specific principle is very simple, I will not say more:
Package data_structure;
Import java.util.ArrayList;
Import java.util.Collection;
Import java.util.Collections;
Import java.util.LinkedList;
Import java.util.List;
public class Huffmantree {public static class node<e>{private E data;
Private Node lchild;
Private Node rchild;
private float weight;
Public Node (E data,float weight) {this.data=data;
This.weight=weight;
Lchild=null;
Rchild=null;
public string toString () {string s= "[Data:" +data.tostring () + ", Weight" +weight+ "]";
return s; }} @SuppressWarnings ({"Rawtypes", "Unchecked"}) public static <E> Node Createtree (list<node> l) {Lis
T<node> list=new arraylist<> ();
List.addall (l);
while (List.size () >1) {quickSort (list);
for (Node node:list) System.out.print (node.data+ "" + (int) node.weight+ "");
System.out.println ();
Node Lchild=list.get (List.size ()-1);
Node Rchild=list.get (List.size ()-2); Node parent=new node ("@", lchild.weight+rChild.weight);
Parent.lchild=lchild;
Parent.rchild=rchild; List.remove (List.size ()-1);
Note that here are minus 1 list.remove (List.size ()-1);
List.add (parent);
Return List.get (0);
/*************** fast **************/public static void QuickSort (List<node> List) {sort (list,0,list.size ()-1); public static void sort (list<node> list,int l,int R) {if (l<r) {int random= (int) (Math.random () * (r-l+1) +l
);
Swap (list, l, random);
int i=l,j=r+1;
Float Value=list.get (l). Weight;
while (true) {//must not be written as I<j because J has been + 1 while (I<r&&list.get (++i). Weight>value);
while (J>l&&list.get (--j). Weight<value);
if (i>=j) break;
Swap (list, I, j);
} Swap (List, L, j);
Sort (list, L, j-1);
Sort (list, j+1, R);
} public static void Swap (list<node> list,int l,int r) {Node tempnode=list.get (l);
List.set (L, List.get (R));
List.set (R, Tempnode); public static void Inorder (Node Root) {if (root==null) return;
Inorder (Root.lchild);
System.out.print (root.tostring () + "");
Inorder (Root.rchild);
public static void Main (String []args) {list