0% found this document useful (0 votes)
4 views

binary search

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

binary search

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Prac No.

9 Binary Search Tree


Aim: To create a Binary Search Tree and use functions related to binary search tre e
Requirement: Python IDE
Code:
class BinarySearchTreeNode:

def __init__(self, data):


self.data = data
self.left = None
self.right = None

def add_child(self, data):


if data == self.data:
return # node already exist

if data < self.data:


if self.left:
self.left.add_child(data)
else:
self.left = BinarySearchTreeNode(data)
else:
if self.right:

self.right.add_child(data)
else:
self.right = BinarySearchTreeNode(data)

def search(self, val):


if self.data == val:
return True

if val < self.data:


if self.left:
return self.left.search(val)

else:
return False

if val > self.data:


if self.right:
return self.right.search(val)
else:
return False

def show(self):
elements = []

if self.left:
elements += self.left.show()

elements.append(self.data)

if self.right:
elements += self.right.show()

return elements

def find_max(self):
if self.right is None:

return self.data
return self.right.find_max()

def find_min(self):

if self.left is None:
return self.data
return self.left.find_min()

def delete(self, val):


if val < self.data:
if self.left:
self.left = self.left.delete(val)
elif val > self.data:
if self.right:
self.right = self.right.delete(val)
else:

if self.left is None and self.right is None:


return None
elif self.left is None:
return self.right

elif self.right is None:


return self.left

min_val = self.right.find_min()

self.data = min_val
self.right = self.right.delete(min_val)

return self

Root= BinarySearchTreeNode(11)
Root.add_child(8)
Root.add_child(9)

Root.add_child(5)
Root.add_child(15)
print(Root.show())
print("If 5 is in tree? : ", Root.search(5))

print("Min value in this tree : ", Root.find_min())


print("Max value in this tree : ", Root.find_max())
Output:

Results: Binary search tree was created by using OOP. Methods like Add_child and delete
were used to insert and delete the elements in tree.

You might also like