我想用 python 写一个树的先序递归。我可以用for语句,但是如果我用list comprehension,我希望通过它的副作用达到递归的效果,为什么不行?
这个方法有效:
def preorder(t):
ret = [label(t)]
for branch in branches(t):
ret.extend(preorder(branch))
return ret
但这并没有给我正确的结果。
def preorder(t):
ret = [label(t)]
a = (ret.extend(preorder(b)) for b in branches(t))
return ret
用第二种方法:
T = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
preorder(T)
回报只有
[1]
树ADT细节
def tree(label, branches=[]):
"""Construct a tree with the given label value and a list of branches."""
for branch in branches:
assert is_tree(branch), 'branches must be trees'
return [label] + list(branches)
def label(tree):
"""Return the label value of a tree."""
return tree[0]
def branches(tree):
"""Return the list of branches of the given tree."""
return tree[1:]