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 implements Comparable>{
  private T data;
  private int weight;
  private Node left;
  private Node right;
   
  public Node (T data,int weight){
    this.data = data;
    this.weight = weight;
  }
   
  public int compareTo(Node 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 getLeft() {
    return left;
  }
 
  public void setLeft(Node left) {
    this.left = left;
  }
 
  public Node getRight() {
    return right;
  }
 
  public void setRight(Node right) {
    this.right = right;
  }  
   
  public String toString(){ 
    return "data:"+this.data+";weight:"+this.weight; 
  } 
}
 
public class huffuman {
  static  Node create(List> nodes){
    while(nodes.size()>1){
      Collections.sort(nodes); 
      Node left = nodes.get(nodes.size()-1);
      Node right = nodes.get(nodes.size()-2);
      Node parent = new Node(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 List> breadth(Node root){
    List> list = new ArrayList>();
    Queue> queue = new ArrayDeque>();
    queue.offer(root);
    while(queue.size()>0){
      Node 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> list = new ArrayList>(); 
    list.add(new Node("a",7)); 
    list.add(new Node("b",5)); 
    list.add(new Node("c",4)); 
    list.add(new Node("d",2)); 
      
    Node root =huffuman.create(list); 
    System.out.println(huffuman.breadth(root)); 
//   System.out.println(list); 
  }
    
   
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(java哈夫曼树实例代码)