Simple and easy way of explanation to get good marks in your academy Educational advancement for the benefit of the public charity In general, to ‘advance’ education means to promote, sustain and increase individual and collective knowledge and understanding of specific areas of study, skills and expertise.
class _Node:
ReplyDelete__slots__ = '_element', '_left', '_right'
def __init__(self, element, left=None, right=None):
self._element = element
self._left = left
self._right = right
class BinaryTree:
def __init__(self):
self._root = None
def maketree(self, e, left, right):
self._root = _Node(e,left._root,right._root)
def inorder(self,troot):
if troot:
self.inorder(troot._left)
print(troot._element,end=' ')
self.inorder(troot._right)
def preorder(self,troot):
if troot:
print(troot._element,end=' ')
self.preorder(troot._left)
self.preorder(troot._right)
def postorder(self,troot):
if troot:
self.postorder(troot._left)
self.postorder(troot._right)
print(troot._element, end=' ')
x = BinaryTree()
y = BinaryTree()
z = BinaryTree()
r = BinaryTree()
s = BinaryTree()
t = BinaryTree()
a = BinaryTree()
x.maketree(40,a,a)
y.maketree(60,a,a)
z.maketree(20,x,a)
r.maketree(50,a,y)
s.maketree(30,r,a)
t.maketree(10,z,s)
print('Inorder Traversal')
t.inorder(t._root)
print()
print('Preorder Traversal')
t.preorder(t._root)
print()
print('Postorder Traversal')
t.postorder(t._root)
output
ReplyDeleteInorder Traversal
40 20 10 50 60 30
Preorder Traversal
10 20 40 30 50 60
Postorder Traversal
40 20 60 50 30 10
Binary search tree
ReplyDeleteclass _Node:
__slots__ = '_element', '_left', '_right'
def __init__(self, element, left=None, right=None):
self._element = element
self._left = left
self._right = right
class BinarySearchTree:
def __init__(self):
self._root = None
def insert(self,troot,e):
temp = None
while troot:
temp = troot
if e == troot._element:
return
elif e < troot._element:
troot = troot._left
elif e > troot._element:
troot = troot._right
n = _Node(e)
if self._root:
if e < temp._element:
temp._left = n
else:
temp._right = n
else:
self._root = n
def inorder(self,troot):
if troot:
self.inorder(troot._left)
print(troot._element,end=' ')
self.inorder(troot._right)
B = BinarySearchTree()
B.insert(B._root,50)
B.insert(B._root,30)
B.insert(B._root,80)
B.insert(B._root,10)
B.insert(B._root,40)
B.insert(B._root,60)
B.insert(B._root,90)
B.inorder(B._root)
output
10 30 40 50 60 80 90