class Tree:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def is_empty(self):
return self.data is None
def insert(self,value):
if value < self.data:
if self.left is None :
self.left = Tree(value)
else:
self.left.insert(value)
if value > self.data :
if self.right is None:
self.right = Tree(value)
else:
self.right.insert(value)
def show_left(self):
current = self.left
while current:
if current.data != None:
print(current.data)
current = current.left
print()
def show_right(self):
current = self.right
while current:
if current.data != None:
print(current.data)
current = current.right
print()
def delete(root):
value=-3
if root:
delete(root.left)
delete(root.right)
if root.data == value and root.data != None:
root.data = None
def preorder(root):
if root and root.data != None:
print(root.data)
preorder(root.left)
preorder(root.right)
def postorder(root):
if root and root.data != None:
postorder(root.left)
postorder(root.right)
print(root.data)
def inorder(root):
if root and root.data != None:
inorder(root.left)
print(root.data)
inorder(root.right)
root = Tree(1)
root.insert(2)
root.insert(3)
root.insert(4)
root.insert(-1)
root.insert(-2)
root.insert(-3)
root.show_left()
root.show_right()
delete(root)
root.show_right()
root.show_left()
preorder(root)
postorder(root)
inorder(root)
No comments:
Post a Comment