package w3ang.algorithms;
import java.util.TreeSet;
class HuffmanNode implements Comparable<Object>{
public int weight;
public boolean original;
public HuffmanNode parent;
public HuffmanNode lchild;
public HuffmanNode rchild;
public HuffmanNode(int weight,boolean original) {
this.weight=weight;
this.original=original;
}
@Override
public int compareTo(Object o) {
if(this.weight<((HuffmanNode)o).weight)
return -1;
else if(this.weight==((HuffmanNode)o).weight)
return 0;
return 1;
}
}
public class HuffmanTree{
private static int Count=0;
public static void main(String[] args) {
TreeSet<HuffmanNode>treeSet=new TreeSet<>();
//1 5 3 6 7 8
treeSet.add(new HuffmanNode(1,true));treeSet.add(new HuffmanNode(5,true));
treeSet.add(new HuffmanNode(3,true));treeSet.add(new HuffmanNode(6,true));
treeSet.add(new HuffmanNode(7,true));treeSet.add(new HuffmanNode(8,true));
//7 2 5 4
/*treeSet.add(new HuffmanNode(7,true));treeSet.add(new HuffmanNode(5,true));
treeSet.add(new HuffmanNode(2,true));treeSet.add(new HuffmanNode(4,true));*/
HuffmanNode minNode=treeSet.first();
/*
* 主要利用Java的引用赋值,默认情况下赋值就是引用方式的,除非=*.clone()才仅仅是copy
* minNode和下面第一次的min指向同一个对象,可以看作两个指针指向同一块内存。。。
* */
while(treeSet.size()>1)
{
HuffmanNode min=treeSet.first();treeSet.remove(treeSet.first());
HuffmanNode min2=treeSet.first();treeSet.remove(treeSet.first());
HuffmanNode pNode=new HuffmanNode(min.weight+min2.weight,false);
min.parent=pNode;//仅仅用来从底部向上遍历,以记录哈夫曼树高度
min2.parent=pNode;//【也不可以省略】,仅仅用来从底部向上遍历,以记录哈夫曼树高度
pNode.lchild=min;
pNode.rchild=min2;
treeSet.add(pNode);
}
int highNum=1;
while(minNode.parent!=null)
{
minNode=minNode.parent;
++highNum;
}
System.out.println("哈夫曼树高度:"+highNum);
//遍历Huffman树,先序遍历
preOrder(treeSet.first(),0);
System.out.println("总权值:"+Count);
}
//计算权值,其实不需要预先获知哈夫曼树高度
private static void preOrder(HuffmanNode hNode,int Num) {
if(hNode==null)
return;
if(hNode.original==true)
Count+=hNode.weight*Num;
System.out.println(hNode.weight+","+Num+","+hNode.original);
++Num;//无论左右孩子,路径都加1
preOrder(hNode.lchild,Num);
preOrder(hNode.rchild,Num);
}
}
/*
哈夫曼树高度:5
30,0,false
13,1,false
6,2,true
7,2,true
17,1,false
8,2,true
9,2,false
4,3,false
1,4,true
3,4,true
5,3,true
总权值:73
*/
哈夫曼树构造方法
假设有n个权值,则构造出的哈夫曼树有n个叶子结点.n个权值分别设为 w1、w2、…、wn,则哈夫曼树的构造规则为:
(1) 将w1、w2、…,wn看成是有n 棵树的森林(每棵树仅有一个结点);
(2) 在森林中选出两个根结点的权值最小的树合并,作为一棵新树的左、右子树,且新树的根结点权值为其左、右子树根结点权值之和;
(3)从森林中删除选取的两棵树,并将新树加入森林;
(4)重复(2)、(3)步,直到森林中只剩一棵树为止
根据上述方法,得到的哈夫曼树,先选1 3 得到4,新的森林即 4 5 6 7 8,选择4 5 得到9,新的森林变为6 7 8 9,选择6 7 得到13,森林变为8 9 13,选择8 9得到17 变为 13 17,选择13 17得到30,只剩最后一个课树.
[30]
/ \
[17] [13]
/ \ / \
(8) [9] (6) (7)
/ \
[4] (5)
/ \
(1) (3)
图片上传不了,按照上述方式弄了一下,()表示叶节点,到时候你用圈就行,[]表示是其下面左右子树的根.
树的带权路径长度规定为所有叶子结点的带权路径长度之和,记为WPL
WPL= 1*4 +3*4 +5*3 + 8*2 + 6*2 + 7*2 = 73