java哈夫曼树实例代码
更新时间:2020年04月28日 09:04:32 作者:稀饭粥95
这篇文章主要为大家介绍了java哈夫曼树实例代码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了哈夫曼树java代码,供大家参考,具体内容如下
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; } 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){ 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 = 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 ArrayList<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>> list = 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); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
springboot中通过jwt令牌校验及前端token请求头进行登录拦截实战记录
这篇文章主要给大家介绍了关于springboot中如何通过jwt令牌校验及前端token请求头进行登录拦截的相关资料,需要的朋友可以参考下2024-08-08简单说明Java的Struts框架中merge标签的使用方法
这篇文章主要简单介绍了Java的Struts框架中merge标签的使用方法,Struts是Java的SSH三大web开发框架之一,需要的朋友可以参考下2015-12-12
最新评论