如何为使用引用引用子树的BinaryTree
类编写反向(自)方法?
def __init__(self, value, l = None, r = None) :
self.data = value
self.left = l
self.right = r
def insert_left(self, value) :
self.left = BinaryTree(value, l = self.left)
def insert_right(self, value) :
self.right = BinaryTree(value, l = self.right)
def set_value(self, value) :
self.data = value
def get_value(self) :
return self.data
def get_left_subtree(self) :
return self.left
def get_right_subtree(self) :
return self.right
def create_string(self, indent) :
info = str(self.data) + '---+'
if self.left :
info += '\n(l)' + indent + self.left.create_string(indent + ' ')
if self.right :
info += '\n(r)' + indent + self.right.create_string(indent + ' ')
return info
def __str__(self) :
representation = self.create_string(" ")
return representation
def reverse(self) :
# reverse(self)
# ===============
# always returns a copy of the tree with the following changes:
# if self has no subtrees then no side-effects
# if self has only one subtree
# then reverses that subtree
# and moves it to the other side
# else reverses both subtrees
# and swaps the two reversed subtrees
#
答案 0 :(得分:0)
def reverse(self):
self.left, self.right = self.right, self.left
if self.left != None:
self.left.reverse()
if self.right != None:
self.right.reverse()