0

我正在写一个树遍历方法。输出需要在一行上。但是,当方法完成后,我想插入一个换行符。有什么方法可以在函数内执行此操作,还是必须从外部调用它?

现在我有:

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

关于如何改变它的任何想法?

4

3 回答 3

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

虽然在外面做可能更干净。

于 2013-02-03T21:52:40.907 回答
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))
于 2013-02-03T21:53:36.380 回答
0

在此函数退出递归后,它将打印一堆节点。之后,在标准输出中添加一个换行符。所以是的,在外面。

于 2013-02-03T21:50:31.223 回答