欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

java哈夫曼树实例代码

时间:2020-12-23 11:59:27|栏目: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); 
 }
  
  
}

上一篇:SWT(JFace)体验之Slider,Scale

栏    目:JAVA代码

下一篇:spring security中的csrf防御原理(跨域请求伪造)

本文标题:java哈夫曼树实例代码

本文地址:http://www.codeinn.net/misctech/35723.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有