答案:
关于如何在输出哈夫曼树时实现横向显示,可以考虑使用递归的方式,将树展开为一行,然后输出每一层的节点。代码如下:
class Node:
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
def build_huffman_tree(data):
# build a huffman tree with given data
nodes = [Node(d) for d in data]
while len(nodes) > 1:
nodes = sorted(nodes, key=lambda x: x.value)
left = nodes.pop(0)
right = nodes.pop(0)
parent = Node(left.value + right.value)
parent.left = left
parent.right = right
nodes.append(parent)
return nodes[0]
def get_depth(node):
# get the depth of a huffman tree
if node is None:
return 0
left_depth = get_depth(node.left)
right_depth = get_depth(node.right)
return max(left_depth, right_depth) + 1
def print_huffman_tree(root, depth):
# print a huffman tree horizontally
if root is None:
return
print_huffman_tree(root.right, depth + 1)
print(' ' * 4 * depth, root.value)
print_huffman_tree(root.left, depth + 1)
data = [10, 15, 12, 3, 4, 13, 1]
root = build_huffman_tree(data)
depth = get_depth(root)
print_huffman_tree(root, depth-1)
这里使用了递归的方式,先将右子树展开,然后输出当前节点的值,最后展开左子树。为了控制每个节点之间的距离,可以在输出前加上一定长度的空格。
具体流程如下: