【笔记】哈夫曼树 哈夫曼树(Huffman Tree)是一种特殊的二叉树,用于数据压缩和编码。它的构建过程是根据字符出现的频率来确定每个字符的编码,使得出现频率高的字符具有较短的编码,而出现频率低的字符具有较长的编码。 以下是一个Python实现的哈夫曼树的例子: “`python class TreeNode: def __init__(self, value, freq): self.value = value self.freq = freq self.left = None self.right = None def build_huffman_tree(char_freq): nodes = [TreeNode(char, freq) for char, freq in char_freq.items()] while len(nodes) > 1: nodes = sorted(nodes, key=lambda x: x.freq) left_node = nodes.pop(0) right_node = nodes.pop(0) parent_node = TreeNode(None, left_node.freq + right_node.freq) parent_node.left = left_node parent_node.right = right_node nodes.append(parent_node) return nodes[0] def encode_huffman_tree(root, code=”, codes={}): if root is None: return if root.value is not None: codes[root.value] = code encode_huffman_tree(root.left, code + ‘0’, codes) encode_huffman_tree(root.right, code + ‘1’, codes) return codes def decode_huffman_tree(root, encoded_text): decoded_text = ” current_node = root for bit in encoded_text: if bit == ‘0’: current_node = current_node.left else: current_node = current_node.right if current_node.value is not None: decoded_text += current_node.value current_node = root return decoded_text # 示例用法 char_freq = {‘a’: 5, ‘b’: 9, ‘c’: 12, ‘d’: 13, ‘e’: 16, ‘f’: 45} huffman_tree = build_huffman_tree(char_freq) huffman_codes = encode_huffman_tree(huffman_tree) encoded_text = ”.join([huffman_codes[char] for char in ‘abcdef’]) decoded_text = decode_huffman_tree(huffman_tree, encoded_text) print(“Huffman Codes:”, huffman_codes) print(“Encoded Text:”, encoded_text) print(“Decoded Text:”, decoded_text) “`
2024最新激活全家桶教程,稳定运行到2099年,请移步至置顶文章:https://sigusoft.com/99576.html
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。 文章由激活谷谷主-小谷整理,转载请注明出处:https://sigusoft.com/40392.html