[英]Construct String from Binary Tree
A bit of a newbie to computing science.有点像计算科学的新手。
I have the basics for a binary tree in Python:我有 Python 中二叉树的基础知识:
class TreeBinary:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
This works well on insertion to popularize the tree:这在插入以普及树时效果很好:
root = TreeBinary(1)
root.left = TreeBinary(2)
root.right = TreeBinary(3)
root.right.right = TreeBinary(4)
One of the challenges that I am trying to discover is how to print this tree in order to show the sub-trees if there is one in the following model:我试图发现的挑战之一是如何打印此树以显示子树(如果以下 model 中有一个):
(1 (2 () ()) (3 () (4 () ())))
(2 () ())
(3 () (4 () ()))
I was able to print, but not in this format with these spaces between the sub-trees:我能够打印,但不能以这种格式打印,子树之间有这些空格:
def show_aux(root):
if not root:
return ''
string = str(root.data)
if root.left or root.right:
string += '(' + show_aux(root.left) + ')'
else:
string += '('
string += ')'
if root.right:
string += '(' + show_aux(root.right) + ')'
else:
string += '('
string += ')'
return string
def show(root):
print('(' + show_aux(root) + ')')
My results are coming out this way:我的结果是这样出来的:
(1(2()())(3()(4()())))
(2()())
(3()(4()()))
I would like a direction to print in the expected format with the spaces between the sub-trees.我想要一个以预期格式打印的方向,子树之间有空格。
Thanks:)谢谢:)
Add spaces before every (
like this在每个之前添加空格
(
像这样
def show_aux(root):
if not root:
return ''
string = str(root.data)
if root.left or root.right:
string += ' (' + show_aux(root.left) + ')' #Space before '('
else:
string += ' (' #Space before '('
string += ')'
if root.right:
string += ' (' + show_aux(root.right) + ')' #Space before '('
else:
string += ' (' #Space before '('
string += ')'
return string
def show(root):
print('(' + show_aux(root) + ')')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.