这是我在这里的第一个问题,如果有问题,请原谅我。
得到一棵编码为 a 的二叉树tuple(node_label, left_node_tuple, right_node_tuple)
,我必须编写一个迭代器/生成器,它按预定顺序返回树的节点。
前任:
输入:('b', ('a', None, None), ('z', ('c', None, None), ('zz', None, None)))
输出:b, a, z, c, zz
我该如何解决?
谢谢
tree = ('b', ('a', None, None), ('z', ('c', None, None), ('zz', None, None)))
def breadth_first(tree):
root, left_sub_tree, right_sub_tree = tree
yield root
for subtree in (left_sub_tree, right_sub_tree):
if subtree is not None:
for element in breadth_first(subtree):
yield element
print list(breadth_first(tree))
输出:
['b', 'a', 'z', 'c', 'zz']