C/C++版本哈夫曼树
具体的概念啥的就不多说了,可以查看C/C++版本或其他渠道了解概念。
由于使用的是Java来编写,那么其实由于Java以及封装好了很多函数来给我们使用,因此开发效率比较快。
直接上代码和效果
运行效果
package test;
import javax.swing.tree.TreeNode;
import java.util.Arrays;
import java.util.Scanner;
class HuffmanCode{
//建立数的节点类
static class Node{
int weight; //权值
int parent; //双亲节数组下标
int leftChild; //左孩子
int rightChild; //右孩子
public Node(int weight,int parent,int leftChild,int rightChild){ //节点初始化
this.weight=weight;
this.parent=parent;
this.leftChild=leftChild;
this.rightChild=rightChild;
}
void setWeight(int weight){
this.weight=weight;
}
void setParent(int parent){
this.parent=parent;
}
void setLeftChild(int leftChild){
this.leftChild=leftChild;
}
void setRightChild(int rightChild){
this.rightChild=rightChild;
}
int getWeight(){
return weight;
}
int getParent(){
return parent;
}
int getLeftChild(){
return leftChild;
}
int getRightChild(){
return rightChild;
}
}
//新建哈夫曼编码 编码类
static class NodeCode{
Character character;
String code;
NodeCode(Character character,String code){
this.character=character;
this.code=code;
}
NodeCode(String code){
this.code= code;
}
void setCharacter(Character character){
this.character=character;
}
void setCode(String code){
this.code=code;
}
Character getCharacter(){
return character;
}
String getCode(){
return code;
}
}
//初始化一个哈夫曼树
public static void initHuffmanTree(Node[] huffmanTree,int m){
for(int i=0;i=0 )
{
start--;
code[start]=((huffmanTree[parent].getLeftChild()==c)?'0':'1');//用于判断它是双亲的左孩子还是右孩子
c=parent;
}
for(;start 


