题解 | #哈夫曼树#

哈夫曼树

https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155

import heapq


class Node:
    def __init__(self, weight):
        self.left = None
        self.right = None
        self.weight = weight

    def __lt__(self, other):
        return self.weight < other.weight


def build_huffman_tree(weights):
    nodes = [Node(w) for w in weights]
    heapq.heapify(nodes)
    while len(nodes) > 1:
        left = heapq.heappop(nodes)
        right = heapq.heappop(nodes)
        parent = Node(left.weight + right.weight)
        parent.left = left
        parent.right = right
        heapq.heappush(nodes, parent)
    return nodes[0]


def encode(root, prefix="", encoding={}):
    if root.left is None and root.right is None:
        encoding[root.weight] = prefix
    if root.left:
        encode(root.left, prefix + "0", encoding)
    if root.right:
        encode(root.right, prefix + "1", encoding)
    return encoding


def get_sum(node, depth):
    if node is None:
        return 0
    if node.left is None and node.right is None:
        return depth * node.weight
    return get_sum(node.left, depth + 1) + get_sum(node.right, depth + 1)


def huffman_tree(weights):
    root_node = build_huffman_tree(weights)
    encoding = encode(root_node)
    return get_sum(root_node, 0)


while True:
    try:
        n = int(input().strip())
        weights = list(map(int, input().strip().split()))
        print(huffman_tree(weights))
    except:
        break

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-24 20:55
阿里国际 Java工程师 2.7k*16.0
程序员猪皮:没有超过3k的,不太好选。春招再看看
点赞 评论 收藏
分享
10-10 17:54
点赞 评论 收藏
分享
牛客5655:其他公司的面试(事)吗
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务