java通过一个字段构造树,Java 树结构实际应用 二(哈夫曼树和哈夫曼编码)

packagecom.lin.HuffmanCode_0314;importjava.util.ArrayList;importjava.util.Collections;importjava.util.HashMap;importjava.util.List;importjava.util.Map;public classHuffmanCode {public static voidmain(String[] args) {

String content= "i like like like java do you like a java";byte[] contentBytes =content.getBytes();

System.out.println(contentBytes.length);//40

List nodes =getNodes(contentBytes);

System.out.println(nodes);//创建哈夫曼树

System.out.println("哈夫曼树");

Node createHuffmanTree=createHuffmanTree(nodes);

preOrder(createHuffmanTree);

}/***

* @Description:生成赫夫曼树对应的赫夫曼编码

* 思路:将赫夫曼编码存放在Map<

*@authorLinZM

* @date 2021-3-14 21:09:30

*@versionV1.8*/

//前序遍历

private static voidpreOrder(Node root){if(root != null) {

root.preOrder();

}else{

System.out.println("空树!");

}

}/***

* @Description:

*@authorLinZM

* @date 2021-3-14 20:45:23

*@versionV1.8

*@parambytes接收字节数组

*@param

*/

private static List getNodes(byte[] bytes){//1 创建一个ArrayList

ArrayList nodes= new ArrayList();//遍历bytes,统计每一个byte出现的次数->map[key, value]

Map counts = newHashMap();for(byteb: bytes) {

Integer count= counts.get(b); //

if(count == null) { //Map中还没有这个字符数据, 第一次

counts.put(b, 1);

}else{

counts.put(b, count+ 1);

}

}//把每个键值对转成一个Node对象, 并加入到nodes集合

for(Map.Entryentry: counts.entrySet()) {

nodes.add(newNode(entry.getKey(), entry.getValue()));

}returnnodes;

}//通过List创建赫夫曼树

private static Node createHuffmanTree(Listnodes) {while(nodes.size() > 1) {

Collections.sort(nodes);

Node leftNode= nodes.get(0);

Node rightNode= nodes.get(1);

Node parent= new Node(null, leftNode.weight +rightNode.weight);

parent.left=leftNode;

parent.right=rightNode;

nodes.remove(leftNode);

nodes.remove(rightNode);

nodes.add(parent);

}return nodes.get(0);

}

}class Node implements Comparable{

Byte data;//存放数据本身

int weight; //权值,字符出现的次数

Node left;

Node right;public Node(Byte data, intweight) {this.data =data;this.weight =weight;

}

@Overridepublic intcompareTo(Node o) {//TODO Auto-generated method stub

return this.weight -o.weight;

}

@OverridepublicString toString() {return "Node [data = " + data + " weight= " + weight + "]";

}//前序遍历

public voidpreOrder() {

System.out.println(this);if(this.left != null) {this.left.preOrder();

}if(this.right != null) {this.right.preOrder();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值