В функции walk я реализовывал вывод дерева, но в итоге она не работает, и я не могу придумать как сделать красивый вывод не прибегая к сильному изменению кода класса BinaryTree.
class ChangeConstantError(AttributeError):
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = None
def __str__(self):
if self.message:
return '{0} '.format(self.message)
else:
return 'ChangeConstantError has been raised'
class BinaryTree:
def __init__(self, value, parents=[], *, parent=None, owner=None):
self.value = value
self.left_child = None
self.right_child = None
self.parent=parent
self.parents=[*parents]
if owner==None: # if it is the parent of the parents, then:
self.depth=0
self.__ownerParent=self if owner==None else owner
#self.current_depth=self.__ownerParent
if owner==None:
self.__ownerParent.depth=0
def current_depth(self):
return len(self.parents)
def __diving(self):
self.ownerParent.depth += 1
@property
def ownerParent(self):
return self.__ownerParent
@ownerParent.getter
def ownerParent(self):
return self.__ownerParent
@ownerParent.setter
def ownerParent(self, value):
raise ChangeConstantError("Can not set a value to the not mutable varible \"ownerParent\"")
def insert_right(self, value):
self.__diving()
if self.right_child == None:
self.right_child = BinaryTree(value, [*self.parents, self], parent=self, owner=self.ownerParent)
else:
new_node = BinaryTree(value, [*self.parents, self], parent=self, owner=self.ownerParent)
new_node.right_child = self.right_child
self.right_child = new_node
def insert_left(self, value):
self.__diving()
if self.left_child == None:
self.left_child = BinaryTree(value, [*self.parents, self], parent=self, owner=self.ownerParent)
else:
new_node = BinaryTree(value, [*self.parents, self], parent=self, owner=self.ownerParent)
new_node.left_child = self.left_child
self.left_child = new_node
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.value}, parent={self.parent})"
def walk(t: BinaryTree) -> None:
"""This function is prints BinaryTree"""
print()
if t.parent==None:
print(" "*(t.current_depth()+1), t.value, " ")
if t.left_child != None:
print(t.left_child.value, end="")
#walk(t.left_child)
if t.right_child != None:
print(" ", t.right_child.value)
#walk(t.right_child)
if t.left_child : walk(t.left_child)
if t.right_child: walk(t.right_child)