# huffman编码

## huffman编码

1. 根据给定的 n 个权值，构造 n 棵只有一个根结点的二叉树， n 个权值分别是这些二叉树根结点的权， F 是由这 n 棵二叉树构成的集合；
2. 在 F 中选取两棵根结点树值最小的树作为左、右子树，构造一颗新的二叉树，置新二叉树根的权值=左子树根结点权值+右子树根结点权值；
3. 从 F 中删除这两颗树，并将新树加入 F；
4. 重复以上步骤，直到只剩下最后一颗树。

## java代码实现

package dataStructureAndAlgorithms;

public class HuffmanTreeNode implements Comparable<HuffmanTreeNode>{
public int getWeight() {
return weight;
}

public void setWeight(int weight) {
this.weight = weight;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public HuffmanTreeNode getLeftChild() {
return leftChild;
}

public void setLeftChild(HuffmanTreeNode leftChild) {
this.leftChild = leftChild;
}

public HuffmanTreeNode getRightChild() {
return rightChild;
}

public void setRightChild(HuffmanTreeNode rightChild) {
this.rightChild = rightChild;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

private String content = null;
private int weight;
private String code = "";
private HuffmanTreeNode leftChild = null;
private HuffmanTreeNode rightChild = null;

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

//Returns:a negative integer, zero, or a positive integer as this object is
//less than, equal to, or greater than the specified object.
public int compareTo(HuffmanTreeNode o) {
if(weight<o.getWeight()){
return -1;
}else if(weight > o.getWeight()){
return 1;
}else{
return 0;
}
}
}


package dataStructureAndAlgorithms;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HuffmanCode {
public static HuffmanTreeNode buildHuffmanTree(List<HuffmanTreeNode> nodes){
int n = nodes.size();
//n-1次
for(int i=1;i<n;i++){
Collections.sort(nodes);

HuffmanTreeNode min1 = nodes.remove(0);
HuffmanTreeNode min2 = nodes.remove(0);
HuffmanTreeNode newNode = new HuffmanTreeNode(min1.getWeight()+min2.getWeight());
newNode.setLeftChild(min1);
newNode.setRightChild(min2);
}
return nodes.get(0);
}

public static void generateHuffmanCode(HuffmanTreeNode root){
if(root.getLeftChild() != null){
root.getLeftChild().setCode(root.getCode() + "0");
generateHuffmanCode(root.getLeftChild());
}

if(root.getRightChild() != null){
root.getRightChild().setCode(root.getCode() + "1");
generateHuffmanCode(root.getRightChild());
}
}

public static void main(String[] args) {
HuffmanTreeNode node1 = new HuffmanTreeNode(3);
node1.setContent("A");
HuffmanTreeNode node2 = new HuffmanTreeNode(1);
node2.setContent("B");
HuffmanTreeNode node3 = new HuffmanTreeNode(2);
node3.setContent("C");
HuffmanTreeNode node4 = new HuffmanTreeNode(1);
node4.setContent("D");

List<HuffmanTreeNode>nodeCopy = new ArrayList<HuffmanTreeNode>();

HuffmanTreeNode root = buildHuffmanTree(nodes);
generateHuffmanCode(root);

for(HuffmanTreeNode node:nodeCopy){
System.out.println(node.getContent() + "->" + node.getCode());
}
}
}

A->0
B->110
C->10
D->111