这是名为 BNode 的类,
class BNode:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return '' % (self.value, self.left, self.right)
并在下面打印
>>> root = BNode('root')
>>> root.left = BNode('left')
>>> root.right = BNode('right')
>>> root.left.left = BNode('left-left')
>>> root.left.right = BNode('left=right')
>>> print root
root (
left (
left-left (
None
None)
left-right (
None
None))
right (
None
None))
Q) 修改类,这样就可以得到如下的结果。
root (
left (
left-left (
None
None)
left-right (
None
None))
right (
None
None))
我的回答如下。
class BNode:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self, level=0):
R = ''
for ele in range(level):
R += '\t'
R += str(self.value)
R += ' ('
R += '\n'
if isinstance(self.left, BNode):
R += BNode.__repr__(self.left, level+1)
else:
for ele in range(level+1):
R += '\t'
R += str(self.left)
R += '\n'
if isinstance(self.right, BNode):
R += BNode.__repr__(self.right, level+1)
else:
for ele in range(level+1):
R += '\t'
R += str(self.right)
R += ')'
return R
但我想知道这是否是这个问题的最佳解决方案。我认为有更好的...有一些有效的方法吗?
提前谢谢~:)