哈夫曼樹的python實現

2021-10-07 23:25:33 字數 1281 閱讀 4052

在刷題過程中遇到了哈夫曼編碼,所以就去看了看哈夫曼樹,哈哈哈,發現了乙個超級棒的漫畫式的部落格: ,看起來超有趣,然後自己嘗試著寫了寫實現哈夫曼樹的**,有不對的地方希望大家多多指正哈~~~

這裡面的結點權重是已經排好序的,如果麼有排序的話,可以使用快排等方法先排好序再實現哈夫曼樹。

# definition for a binary tree node.

class treenode:

def __init__(self, x):

self.val = x

self.left = none

self.right = none

class solution:

def __init__(self):

self.cur_tree = none

def huffmantree(self, weights, forest):

while len(weights) > 1:

tree = treenode(none)

tree.left = forest[0]

tree.right = forest[1]

tree.val = weights[0] + weights[1]

weights.pop(0)

weights.pop(0)

forest.pop(0)

forest.pop(0)

fathernode = tree.val

a = len(weights)

for i in range(0, len(weights)):

if fathernode <= weights[i]:

weights = weights[:i] + [fathernode] + weights[i:]

forest = forest[:i] + [tree] + forest[i:]

break

elif i == len(weights) - 1 and fathernode > weights[i]:

weights = weights + [fathernode]

forest = forest + [tree]

return tree

if __name__ == '__main__':

weights = [2, 3, 7, 9, 18, 25]

forest =

for w in weights:

solution().huffmantree(weights, forest)

Python 實現哈夫曼樹和哈夫曼編碼

技術部落格 下面主要來看一下哈夫曼樹的 python 實現 usr bin env python coding utf 8 統計字元出現頻率,生成對映表 defcount frequency text chars ret for char in text if char in chars conti...

哈夫曼樹與哈夫曼編碼的實現 python

建立節點類,用於每個節點的生成 class hfmnode def init self self.name none self.weight none self.leftchild none self.rightchild none self.parent none 構建哈夫曼樹 def creat...

哈夫曼編碼 哈夫曼樹

1.定義 哈夫曼編碼主要用於資料壓縮。哈夫曼編碼是一種可變長編碼。該編碼將出現頻率高的字元,使用短編碼 將出現頻率低的字元,使用長編碼。變長編碼的主要問題是,必須實現非字首編碼,即在乙個字符集中,任何乙個字元的編碼都不是另乙個字元編碼的字首。如 0 10就是非字首編碼,而0 01不是非字首編碼。2....