哈夫曼树的python实现

在刷题过程中遇到了哈夫曼编码,所以就去看了看哈夫曼树,哈哈哈,发现了一个超级棒的漫画式的博客:https://baijiahao.baidu.com/s?id=1663514710675419737&wfr=spider&for=pc ,看起来超有趣,然后自己尝试着写了写实现哈夫曼树的代码,有不对的地方希望大家多多指正哈~~~

这里面的结点权重是已经排好序的,如果么有排序的话,可以使用快排等方法先排好序再实现哈夫曼树。

# 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:
        forest.append(TreeNode(w))
    Solution().huffmantree(weights, forest)

 

你可能感兴趣的:(哈夫曼,python)