哈夫曼树的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)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值