Python:在递归函数后打印新行

0 投票
3 回答
1282 浏览
提问于 2025-04-17 14:38

我正在写一个遍历树的函数。这个函数的输出需要在一行上。不过,当这个函数完成后,我想插入一个换行符。有没有办法在函数内部做到这一点,还是说必须在外部调用才能实现?

现在我有:

def postorder_transversal(self):
    if self.node == None:
        return 0
    for child in self.children:
        child.postorder_transversal()
    print self.node,

你有什么想法可以改进它吗?

3 个回答

0

这个函数在完成递归后,会打印出一堆节点。然后,紧接着在标准输出中添加一个换行符。所以没错,换行符是在外面的。

2

你可以把深度作为一个参数传递:

def postorder_transversal(self, depth=0):
    if self.node == None:
        return 0

    for child in self.children:
        child.postorder_transversal(depth=depth + 1)

    print self.node,

    if depth == 0:
        print

然后使用 print 函数:

from __future__ import print_function

def postorder_transversal(self, depth=0):
    if self.node == None:
        return 0

    for child in self.children:
        child.postorder_transversal(depth=depth + 1)

    print(self.node, end='\n' * (depth == 0))
2

你可以在函数里面这样做:

def postorder_transversal(self, add_newline=True):
    if self.node == None:
        return 0
    for child in self.children:
        child.postorder_transversal(add_newline=False)
    print self.node,
    if add_newline:
        print

不过,把它放在外面可能会更整洁一些。

撰写回答