时间:2021-05-19
本文实例为大家分享了哈夫曼树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); } }以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
前言本篇章主要介绍哈夫曼树及哈夫曼编码,包括哈夫曼树的一些基本概念、构造、代码实现以及哈夫曼编码,并用Python实现。1.基本概念哈夫曼树(Huffman(H
本文实例为大家分享了C语言实现哈夫曼树的具体代码,供大家参考,具体内容如下//哈夫曼树C语言实现#include#includetypedefstructHuf
如何建立哈夫曼树的,网上搜索一堆,这里就不写了,直接给代码。1.哈夫曼树结点类:HuffmanNode.h#ifndefHuffmanNode_h#define
一哈夫曼树以及文件压缩原理:1.哈夫曼树:给定N个权值作为N个叶子结点,构造一棵二叉树,若该树的带权路径长度达到最小,称这样的二叉树为最优二叉树,也称为哈夫曼树
本文实例讲述了基于C++实现的哈夫曼编码解码操作。分享给大家供大家参考,具体如下:哈夫曼编码是一个通过哈夫曼树进行的一种编码,一般情况下,以字符:‘0'与‘1'