【发布时间】:2018-11-01 15:12:08
【问题描述】:
给定一个包含 n 个字符的文本和一个由 Huffman 编码生成的二叉树,使得叶节点具有属性:一个字符串(字符本身)和一个整数(它在文本中的频率)。从根到任何叶子的路径代表它的代码字。
我想写一个递归函数来计算压缩文本的长度并找到它的大 O 复杂度。
例如,如果我有文本
abaccab
每个字符在霍夫曼树中都有相关的频率和深度:
4
/ \
a:3 5
/ \
b:2 c:2
那么压缩文本的总长度是11
我想出了这个,但看起来很粗糙:
def get_length(node, depth):
#Leaf node
if node.left_child is None and node.right_child is None:
return node.freq*depth
#Node with only one child
elif node.left_child is None and node.right_child is not None:
return get_length(node.right_child, depth+1)
elif node.right_child is None and node.left_child is not None:
return get_length(node.left_child, depth+1)
#Node with two children
else:
return get_length(node.left_child, depth+1) + get_length(node.right_child, depth+1)
get_length(root,0)
复杂度:O(log 2n) 其中 n 是字符数。
我该如何改进呢?这种情况下的复杂性是什么?
【问题讨论】:
标签: python time-complexity binary-tree huffman-code