Answer the question
In order to leave comments, you need to log in
How to print a binary tree?
In the walk function, I implemented the output of the tree, but in the end it does not work, and I cannot figure out how to make a beautiful output without resorting to a strong change in the code of the BinaryTree class.
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)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question