赫夫曼树
2019-06-17 本文已影响0人
RalapHao
带权路径最短的树,
构建赫夫曼树的思路
- 排序,将最小与次小转为节点,并根据权生成父节点,将父节点加入到结合,
- 移除最小与次小元素,再次排序,重复1
- 直到集合只有一个元素
public class HuffmanTree {
public static void main(String[] args) {
int[] array = {13, 7, 8, 3, 29, 6, 1};
List<Node> list = new ArrayList<>();
Node node = null;
for (int i = 0; i < array.length; i++) {
list.add(new Node(array[i]));
}
HuffmanTree ht = new HuffmanTree();
Node root = ht.createHuffman(list);
ht.preOrder(root);
}
public Node createHuffman(List<Node> list) {
if (list.size() <= 1) {
return list.get(0);
}
Collections.sort(list);
Node node1 = list.get(0);
Node node2 = list.get(1);
Node parent = new Node(node1.value + node2.value);
parent.left = node1;
parent.right = node2;
list.set(0, parent);
list.remove(1);
return createHuffman(list);
}
public void preOrder(Node node) {
node.preOrder(node);
}
}
class Node implements Comparable<Node> {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Node{");
sb.append("value=").append(value);
sb.append('}');
return sb.toString();
}
@Override
public int compareTo(Node o) {
return this.value - o.value;
}
public void preOrder(Node node) {
System.out.println(node);
if (node.left != null) {
preOrder(node.left);
}
if (node.right != null) {
preOrder(node.right);
}
}
}