哈夫曼樹構造

2021-09-13 14:46:13 字數 2850 閱讀 4689

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

"""created on fri jul 27 18:08:26 2018

@author: luogan

"""# 樹節點類構建

class

treenode

(object):

def__init__

(self, data):

self.val = data[0]

self.priority = data[1]

self.leftchild = none

self.rightchild = none

self.code = ""

# 建立樹節點佇列函式

defcreatnodeq

(codes):

q =

for code in codes:

return q

# 為佇列新增節點元素,並保證優先度從大到小排列

defaddq

(queue, nodenew):

if len(queue) == 0:

return [nodenew]

for i in range(len(queue)):

if queue[i].priority >= nodenew.priority:

return queue[:i] + [nodenew] + queue[i:]

return queue + [nodenew]

# 節點佇列類定義

class

nodeqeuen

(object):

def__init__

(self, code):

self.que = creatnodeq(code)

self.size = len(self.que)

defaddnode

(self,node):

self.que = addq(self.que, node)

self.size += 1

defpopnode

(self):

self.size -= 1

return self.que.pop(0)

# 各個字元在字串**現的次數,即計算優先度

deffrechar

(string):

d ={}

for c in string:

ifnot c in d:

d[c] = 1

else:

d[c] += 1

return sorted(d.items(),key=lambda x:x[1])

# 建立哈夫曼樹

defcreathuffmantree

(nodeq):

while nodeq.size != 1:

node1 = nodeq.popnode()

node2 = nodeq.popnode()

r = treenode([none, node1.priority+node2.priority])

r.leftchild = node1

r.rightchild = node2

nodeq.addnode(r)

return nodeq.popnode()

codedic1 = {}

codedic2 = {}

# 由哈夫曼樹得到哈夫曼編碼表

defhuffmancodedic

(head, x):

global codedic, codelist

if head:

huffmancodedic(head.leftchild, x+'0')

head.code += x

if head.val:

codedic2[head.code] = head.val

codedic1[head.val] = head.code

huffmancodedic(head.rightchild, x+'1')

# 字串編碼

deftransencode

(string):

global codedic1

transcode = ""

for c in string:

transcode += codedic1[c]

return transcode

# 字串解碼

deftransdecode

(stringcode):

global codedic2

code = ""

ans = ""

for ch in stringcode:

code += ch

if code in codedic2:

ans += codedic2[code]

code = ""

return ans

# 舉例

string = "aaggdcccdddgfbbbffggddddgggeffddccccddfgaaa"

t = nodeqeuen(frechar(string))

tree = creathuffmantree(t)

huffmancodedic(tree, '')

print(codedic1,codedic2)

a = transencode(string)

print(a)

aa = transdecode(a)

print(aa)

print(string == aa)

posted on 2018-07-27 18:14收藏

構造哈夫曼樹 哈夫曼編碼

1.權值越大的節點,距離根越近 2.樹中沒有度為1的節點,這類樹叫正則 嚴格 二叉樹,樹的總節點 2 雙分支結點 1 單分支結點 雙分支結點 3.樹的帶權路勁 wpl 所有葉子結點的帶權長度路勁之和 長度最短。嗶哩嗶哩王卓老師的口訣 構造森林全是根,選用兩小選新樹,刪除兩小添新人,重複23剩單根 1...

哈夫曼樹構造 哈夫曼編碼

一 哈夫曼樹 p189 1.定義 帶權路徑長度 wpl 最小的二叉樹稱為哈夫曼樹 wpl 樹中所有葉子節點的帶權路徑長度之和 帶權路徑長度 從樹根到任意節點的路徑長度與該節點上權值的乘積 2.構造 1 將這n個節點分別作為n課僅含乙個結點的二叉樹,構成森林f 2 構造乙個新節點,從f中選取兩棵根節點...

哈夫曼樹的構造與哈夫曼編碼

include include include define n 20 葉子結點最大值 define m 2 n 1 所有結點最大值 靜態三叉鍊錶實現哈夫曼樹 typedef struct huffmanhuf node,huf tree m 1 儲存哈夫曼編碼串的頭指標陣列 由於每個哈夫曼編碼是變...