最優二叉樹 指帶權路徑長度最短的樹
class
heapnode
:def
__init__
(self, char=
none
, weight=
none
, left=
none
, right=
none):
self.char = char
self.weight = weight
self.left = left
self.right = right
def__lt__
(self, other)
:return self.weight < other.weight
from itertools import groupby
from heapq import
*class
huffmantree
:def
__init__
(self)
: self.codes =
defbuild
(self, text)
:# 使用heapq構建最小堆,生成haffman樹
minheap =
[heapnode(char,
len(
list
(times)))
for char, times in groupby(
sorted
(text))]
# groupby為分類並統計出現次數
heapify(minheap)
# heapify之後的為列表,按weight排好
while
len(minheap)
>1:
# 取出最小的
# 取出最小的
parent = heapnode(
none
, left.weight + right.weight)
# 將它們並在一起
parent.left = left
parent.right = right
# 並在一起的父結點再入堆,重複找兩個最小的
return minheap # 最終列表長度為1,huffman樹的根節點為minheap[0]
defmake_codes
(self, code, node)
:if node.char:
# 只有葉子節點才有char
ifnot code:
# 對於樹的depth為1
self.codes[node.char]
="0"
else
: self.codes[node.char]
= code
= node.char
else
: self.make_codes(code +
"0", node.left)
# 左子樹編碼為0
self.make_codes(code +
"1", node.right)
# 右子樹編碼為1
defencoded_text
(self, text)
: encoded_text =
""for character in text:
encoded_text += self.codes[character]
return encoded_text
defdecode_text
(self, encoded_text)
: current_code =
"" decoded_text =
""for bit in encoded_text:
current_code += bit
decoded_text += character
current_code =
""return decoded_text
defwpl(self,subtree,depth)
:if subtree.left is
none
and subtree.right is
none
:# 只有為葉子結點時,才計算權長
return depth*subtree.weight
else
:return self.wpl(subtree.left,depth+1)
+ self.wpl(subtree.right,depth+1)
# 非葉子節點,遞迴的計算它的左右子樹的權長
def
test_huffman()
: ht = huffmantree(
) text =
'hhhhhhhhhellllllooo'
httree = ht.build(text)
# 根據text中字元出現的頻率來構建一顆huffman樹
ht.make_codes(
'', httree[0]
)# 對葉子結點的字元編碼
print
(ht.codes)
# 字元對應的編碼
print
# 編碼對應的字元
encode = ht.encoded_text(
"hello"
) text_ = ht.decode_text(encode)
print
('code:'
,encode)
# code: 01001111101
print
('text:'
,text_)
# text: hello
print
('wpl:'
,ht.wpl(httree[0]
,0))
# huffman樹的權長最小 wpl: 33
由測試結果已知:
reference:小碼哥mj
樹 哈夫曼樹(Huffman Tree)
哈夫曼樹 樹的帶權路徑長度達到最小。1.將w1 w2 wn看成是有n 棵樹的森林 每棵樹僅有乙個結點 2.在森林中選出根結點的權值最小的兩棵樹進行合併,作為一棵新樹的左 右子樹,且新樹的根結點權值為其左 右子樹根結點權值之和 3.從森林中刪除選取的兩棵樹,並將新樹加入森林 4.重複 02 03 步,...
哈夫曼樹 Huffman tree 原理
source 1.哈夫曼樹的基本概念 哈夫曼樹 huffman 又稱最優二叉樹,是一類帶權路徑長度最短的樹,有著廣泛的應用。在討論哈夫曼樹之前首先需要弄清楚關於路徑和路徑長度的概念。樹中兩個結點之間的路徑由乙個結點到另一結點的分支構成。兩結點之間的路徑長度是路徑上分支的數目。樹的路徑長度是從根結點到...
HuffmanTree,哈夫曼樹的原理和c 實現
目錄哈夫曼樹又稱為最優樹.通過權值來構造樹,權值越大,離根節點越近 經常用於無失真壓縮演算法 用於需要優化儲存空間的場景 原理很簡單,不多贅述 需要注意 構建哈夫曼樹不僅要值,還需要對應的權值 比如越常出現的,權值越大 通過權值來構造哈夫曼樹 我畫了幾個圖,具體過程如下 上面通過權值構建了哈夫曼樹,...