本质上,我有这个二叉树:
我想做的是遍历它,所以我得到了一条返回值+ BA的str。为此,我具有以下功能:
def order(root):
if (root != None):
root.visit() # this calls a binary tree function that just prints out root.data
order(root.right)
order(root.left)
这很好并且很好,但是我需要返回一个str而不是打印每个遍历。我尝试创建一个str,然后执行str + = root.visit(),但是每次都会重置一次,所以最终它不起作用。如何返回包含所有遍历的字符串?
我试过的
def order(root):
rep = ""
if (root != None):
rep += root.visit()
order(root.right)
order(root.left)
return rep
为了预遍历二叉树,您应该遵循以下方案:
def traverse(node):
rep = ""
if node is not None:
rep += node.visit()
rep += traverse(node.right)
rep += traverse(node.left)
return rep
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句