Reputation: 7879
I'm writing a tree traversal method. The output needs to be on one line. When the method is complete, though, I'd like to insert a line break. Is there any way to do this within the function, or will it have to be called from outside?
Right now I have:
def postorder_transversal(self):
if self.node == None:
return 0
for child in self.children:
child.postorder_transversal()
print self.node,
Any thoughts on how to alter it?
Upvotes: 0
Views: 1333
Reputation: 298096
You could pass the depth as a parameter:
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
And with the print
function:
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))
Upvotes: 2
Reputation: 28846
You could do it inside the function like so:
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
though it may be cleaner to just do it outside.
Upvotes: 2
Reputation:
After this function backs out of recursion, it will print a bunch of nodes. Right after that, add a newline to stdout. So yes, outside.
Upvotes: 0