# 什么是哈夫曼树

7 篇文章 4 订阅

—————  第二天  —————

public class HuffManDemo {
private Node root;
private Node[] nodes;

public static void main(String[] args) {
int[] weights = {2, 3, 7, 9, 18, 25};
HuffManDemo huffManDemo = new HuffManDemo();
huffManDemo.createHuffman(weights);
huffManDemo.output(huffManDemo.root);
}

// 构建哈夫曼树
public void createHuffman(int[] weights) {
//优 先队列，用于辅助构建哈夫曼树
Queue<Node> nodeQueue = new PriorityQueue<>();
nodes = new Node[weights.length];

// 构建森林，初始化nodes数组
for (int i = 0; i < weights.length; i++) {
nodes[i] = new Node(weights[i]);
}
// 主循环，当结点队列只剩一个结点时结束
while (nodeQueue.size() > 1) {
//从结点队列选择权值最小的两个结点
Node left = nodeQueue.poll();
Node right = nodeQueue.poll();
//创建新结点作为两结点的父节点
Node parent = new Node(left.weight + right.weight, left, right);
}
root = nodeQueue.poll();
}

// 按照前序遍历输出
return;
}
}

public static class Node implements Comparable<Node> {
int weight;
Node lChild;
Node rChild;

public Node(int weight) {
this.weight = weight;
}

public Node(int weight, Node lChild, Node rChild) {
this.weight = weight;
this.lChild = lChild;
this.rChild = rChild;
}

@Override
public int compareTo(Node o) {
return new Integer(this.weight).compareTo(new Integer(o.weight));
}
}
}

64
25
39
18
21
9
12
5
2
3
7

• 15
点赞
• 33
收藏
觉得还不错? 一键收藏
• 5
评论
06-17 1万+
06-24 367
06-21 286
03-16 1万+
06-09 870
07-20 2540
08-05 30万+
07-01 872
09-01 965

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