0% found this document useful (0 votes)
36 views8 pages

BST @62

Uploaded by

Abhinay Palle
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)
36 views8 pages

BST @62

Uploaded by

Abhinay Palle
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/ 8

Laboratory record of: Roll no: 160123749062

DATA STRUCTURES
Date:

Aim: Implementation of Binary Search Tree Operations

Description:

A Binary Search Tree (BST) is a data structure that maintains elements in a sorted order, allowing for efficient search,
insertion, and deletion operations. Each node in a BST contains a key (value), and each node has at most two
children, referred to as the left and right children. The left child contains values less than the parent node, while the
right child contains values greater than the parent node.

Key Characteristics of a BST:

1. Ordered Structure:

o For any given node:

▪ All values in the left subtree are less than the node’s value.

▪ All values in the right subtree are greater than the node’s value.

2. Unique Values:

o In a standard BST, each value is unique. However, variations can allow duplicate values.

3. Dynamic Size:

o A BST can grow and shrink dynamically as elements are inserted and deleted.

Common Operations:

1. Insertion:

o Insert a new value into the BST while maintaining the ordering property.

o Start at the root and recursively find the correct position for the new value.

2. Search:

o Find a value in the BST.

o Start at the root and recursively traverse left or right depending on whether the value is less than or
greater than the current node’s value.

3. Deletion:

o Remove a value from the BST while maintaining the ordering property.

o There are three cases:

1. Node to be deleted is a leaf (no children).

2. Node to be deleted has one child.

3. Node to be deleted has two children (replace with the minimum value from the right
subtree or maximum from the left subtree).
Laboratory record of: Roll no: 160123749062
DATA STRUCTURES
Date:

4. Traversal:

o In-Order Traversal: Visits nodes in ascending order. Left subtree, root, right subtree.

Pre-Order Traversal: Visits

o nodes in the order of root, left subtree, right subtree.

o Post-Order Traversal: Visits nodes in the order of left subtree, right subtree, root.

5. Finding Minimum and Maximum:

o Minimum: Traverse left until the leftmost node is reached.

o Maximum: Traverse right until the rightmost node is reached.

Analysis:

Time Complexity:

● Insertion: O(h), where h is the height of the tree. In a balanced BST, this is O(log n); in the worst case
(unbalanced), it can be O(n).

● Search: O(h), with the same considerations as insertion.

● Deletion: O(h), with the same considerations.

● Traversal: O(n), where n is the number of nodes.

Space Complexity:

● The space complexity for operations (other than the space used for the BST itself) is O(h) due to the
recursive stack in function calls, where h is the height of the tree.

Algorithm:

1. Insertion Function: insert(key)

● Input: key (the value to be inserted)

● Output: None (updates the tree)

Steps:

1. If the tree is empty (root is None):

o Create a new node with the given key and assign it as the root.

2. Otherwise, call the recursive helper function _insert_recursive(node, key) with the root node.

2. Search Function: search(key)

● Input: key (the value to be searched)

● Output: Node containing the key or None


Laboratory record of: Roll no: 160123749062
DATA STRUCTURES
Date:

Steps:

1. Call the recursive helper function _search_recursive(node, key) with the root node.

3. Deletion Function: delete(key)

● Input: key (the value to be deleted)

● Output: None (updates the tree)

Steps:

1. Call the recursive helper function _delete_recursive(node, key) with the root node.

4. In-Order Traversal Function: in_order_traversal()

● Input: None

● Output: List of values in ascending order

5. Pre-Order Traversal Function: pre_order_traversal()

● Input: None

● Output: List of values in pre-order sequence

6. Post-Order Traversal Function: post_order_traversal()

● Input: None

● Output: List of values in post-order sequence

CODE :

class TreeNode:

def __init__(self, key):

self.left = None

self.right = None

self.val = key

class BinarySearchTree:

def __init__(self):

self.root = None

def insert(self, key):

if self.root is None:

self.root = TreeNode(key)
Laboratory record of: Roll no: 160123749062
DATA STRUCTURES
Date:

else:

self._insert_recursive(self.root, key)

def _insert_recursive(self, node, key):

if key < node.val:

if node.left is None:

node.left = TreeNode(key)

else:

self._insert_recursive(node.left, key)

else: # Assume no duplicates for this example

if node.right is None:

node.right = TreeNode(key)

else:

self._insert_recursive(node.right, key)

def search(self, key):

return self._search_recursive(self.root, key)

def _search_recursive(self, node, key):

if node is None or node.val == key:

return node

if key < node.val:

return self._search_recursive(node.left, key)

return self._search_recursive(node.right, key)

def delete(self, key):

self.root = self._delete_recursive(self.root, key)

def _delete_recursive(self, node, key):

if node is None:

return node

if key < node.val:

node.left = self._delete_recursive(node.left, key)


Laboratory record of: Roll no: 160123749062
DATA STRUCTURES
Date:

elif key > node.val:

node.right = self._delete_recursive(node.right, key)

else:

if node.left is None:

return node.right

elif node.right is None:

return node.left

min_larger_node = self._min_value_node(node.right)

node.val = min_larger_node.val

node.right = self._delete_recursive(node.right, min_larger_node.val)

return node

def _min_value_node(self, node):

current = node

while current.left is not None:

current = current.left

return current

def in_order_traversal(self):

return self._in_order_recursive(self.root)

def _in_order_recursive(self, node):

return self._in_order_recursive(node.left) + [node.val] + self._in_order_recursive(node.right) if node else []

def pre_order_traversal(self):

return self._pre_order_recursive(self.root)

def _pre_order_recursive(self, node):

return [node.val] + self._pre_order_recursive(node.left) + self._pre_order_recursive(node.right) if node else []

def post_order_traversal(self):

return self._post_order_recursive(self.root)

def _post_order_recursive(self, node):

return self._post_order_recursive(node.left) + self._post_order_recursive(node.right) + [node.val] if node else []


Laboratory record of: Roll no: 160123749062
DATA STRUCTURES
Date:

def main():

bst = BinarySearchTree()

while True:

print("\nMenu:")

print("1. Insert a value")

print("2. Search for a value")

print("3. Delete a value")

print("4. In-order traversal")

print("5. Pre-order traversal")

print("6. Post-order traversal")

print("7. Exit")

choice = input("Choose an option (1-7): ")

if choice == '1':

value = int(input("Enter value to insert: "))

bst.insert(value)

print(f"Inserted {value} into the BST.")

elif choice == '2':

value = int(input("Enter value to search for: "))

found_node = bst.search(value)

if found_node:

print(f"Node {value} found in the BST.")

else:

print(f"Node {value} not found in the BST.")

elif choice == '3':

value = int(input("Enter value to delete: "))

bst.delete(value)

print(f"Deleted {value} from the BST.")

elif choice == '4':


Laboratory record of: Roll no: 160123749062
DATA STRUCTURES
Date:

print("In-order traversal:", bst.in_order_traversal())

elif choice == '5':

print("Pre-order traversal:", bst.pre_order_traversal())

elif choice == '6':

print("Post-order traversal:", bst.post_order_traversal())

elif choice == '7':

print("Exiting...")

break

else:

print("Invalid choice. Please try again.")

if __name__ == "__main__":

main()

Output:

Menu:

1. Insert a value

2. Search for a value

3. Delete a value

4. In-order traversal

5. Pre-order traversal

6. Post-order traversal

7. Exit

Choose an option (1-7): 1


Enter value to insert: 50
Inserted 50 into the BST.

Menu:

1. Insert a value

2. Search for a value

3. Delete a value

4. In-order traversal

5. Pre-order traversal
Laboratory record of: Roll no: 160123749062
DATA STRUCTURES
Date:

6. Post-order traversal

7. Exit

Choose an option (1-7): 1


Enter value to insert: 30
Inserted 30 into the BST.

Menu:

1. Insert a value

2. Search for a value

3. Delete a value

4. In-order traversal

5. Pre-order traversal

6. Post-order traversal

7. Exit

Choose an option (1-7): 7


Exiting...

Result:
The binary search tree (BST) is successfully implemented.

You might also like