java哈夫曼树实例代码
本文实例为大家分享了哈夫曼树java代码,供大家参考,具体内容如下
packageboom; importjava.util.ArrayDeque; importjava.util.ArrayList; importjava.util.Collections; importjava.util.List; importjava.util.Queue; classNode<T>implementsComparable<Node<T>>{ privateTdata; privateintweight; privateNode<T>left; privateNode<T>right; publicNode(Tdata,intweight){ this.data=data; this.weight=weight; } publicintcompareTo(Node<T>other){ if(this.weight>other.getWeight()){ return-1; }if(this.weight<other.getWeight()){ return1; } return0; } publicTgetData(){ returndata; } publicvoidsetData(Tdata){ this.data=data; } publicintgetWeight(){ returnweight; } publicvoidsetWeight(intweight){ this.weight=weight; } publicNode<T>getLeft(){ returnleft; } publicvoidsetLeft(Node<T>left){ this.left=left; } publicNode<T>getRight(){ returnright; } publicvoidsetRight(Node<T>right){ this.right=right; } publicStringtoString(){ return"data:"+this.data+";weight:"+this.weight; } } publicclasshuffuman<T>{ static<T>Node<T>create(List<Node<T>>nodes){ while(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=newNode<T>(null,left.getWeight()+right.getWeight()); parent.setRight(right); parent.setLeft(left); nodes.remove(left); nodes.remove(right); nodes.add(parent); } returnnodes.get(0); } static<T>List<Node<T>>breadth(Node<T>root){ List<Node<T>>list=newArrayList<Node<T>>(); Queue<Node<T>>queue=newArrayDeque<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()); } } returnlist; } publicstaticvoidmain(String[]args){ //TODOAuto-generatedmethodstub List<Node<String>>list=newArrayList<Node<String>>(); list.add(newNode<String>("a",7)); list.add(newNode<String>("b",5)); list.add(newNode<String>("c",4)); list.add(newNode<String>("d",2)); Node<String>root=huffuman.create(list); System.out.println(huffuman.breadth(root)); //System.out.println(list); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。