哈夫曼树与哈夫曼编码的实现——python
#创建节点类,用于每个节点的生成
class hfmNOde():
def __init__(self):
self.name = None
self.weight = None
self.leftchild = None
self.rightchild = None
self.parent = None
#构建哈夫曼树
def CreatTree(data):
#将传入的数据字典,key和value对换,便于后面使用
new_dict = {v : k for k, v in data.items()}
#生成权重列表,用于后面生成哈夫曼树
weight=[i for i in new_dict ]
#生成节点字典,用于储存各个节点,key为每个节点权重,value为对应节点
#节点属性填入name属性和weight属性
node_dict={}
for i in new_dict:
node=hfmNOde()
node.name=new_dict[i]
node.weight=i
node_dict[i]=node
#构建哈夫曼树,直到只剩一个根节点结束构建
#每两个权重最小节点生成一个父节点
while len(weight) != 1:
#找到最小两个权重节点,在权重列表中去除
min1=min(weight)
weight.remove(min1)
min2=min(weight)
weight.remove(min2)
#生成父节点
#父节点左孩子为最小权重节点,右孩子为倒数第二权重节点
#父节点权重为两个孩子权重和
parentNode=hfmNOde()
parentNode.leftchild=node_dict[min1]
parentNode.rightchild=node_dict[min2]
parentNode.weight=min1+min2
#将两个孩子的parent属性都设为该父节点
node_dict[min1].parent=parentNode
node_dict[min2].parent=parentNode
#将父节点权重加入权重列表,并在节点字典中生成对应数据(key为权重,value为节点)
weight.append(parentNode.weight)
node_dict[parentNode.weight]=parentNode
return parentNode
#哈夫曼树解码
#利用递归进行解码
def hfmcode(tree,code="",dict={}):
#若左孩子存在,code加1,若退出该左孩子,则将code最后一个减去
if tree.leftchild:
code=code+"1"
dict=hfmcode(tree.leftchild,code,dict)
code=code[0:-1]
#与上述相同
if tree.rightchild:
code=code+"0"
dict=hfmcode(tree.rightchild,code,dict)
code=code[0:-1]
#若左右孩子不存在,说明到达根节点
#储存当前节点的属性及编码
if tree.leftchild == None and tree.rightchild == None:
dict[tree.name]=code
return dict
data={"a":45,"b":13,"c":12,"d":16,"e":9,"f":5}
tree=CreatTree(data)
print(hfmcode(tree))