Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
25 views2 pages

Binary Search Tree

The document defines a binary search tree (BST) class with methods to insert nodes, search for nodes, and perform an inorder traversal. It also includes a main function that allows a user to interactively insert nodes, search for nodes, and view inorder traversals of the BST.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views2 pages

Binary Search Tree

The document defines a binary search tree (BST) class with methods to insert nodes, search for nodes, and perform an inorder traversal. It also includes a main function that allows a user to interactively insert nodes, search for nodes, and view inorder traversals of the BST.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

class TreeNode:

def __init__(self, key):


self.val = key
self.left = None
self.right = None

class BST:
def __init__(self):
self.root = None

def insert(self, key):


if not self.root:
self.root = TreeNode(key)
else:
self._insert_recursive(self.root, key)

def _insert_recursive(self, node, key):


if key < node.val:
if node.left:
self._insert_recursive(node.left, key)
else:
node.left = TreeNode(key)
else:
if node.right:
self._insert_recursive(node.right, key)
else:
node.right = TreeNode(key)

def search(self, key):


return self._search_recursive(self.root, key)

def _search_recursive(self, node, key):


if not node 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 inorder_traversal(self):
result = []
self._inorder_traversal_recursive(self.root, result)
return result

def _inorder_traversal_recursive(self, node, result):


if node:
self._inorder_traversal_recursive(node.left, result)
result.append(node.val)
self._inorder_traversal_recursive(node.right, result)

def main():
bst = BST()
print("Binary Search Tree Operations:")
print("1. Insert")
print("2. Search")
print("3. Inorder Traversal")
print("4. Exit")
while True:
choice = input("Enter your choice: ")
if choice == '1':
key = int(input("Enter the value to insert: "))
bst.insert(key)
print(f"{key} inserted into the tree.")
elif choice == '2':
key = int(input("Enter the value to search: "))
result = bst.search(key)
if result:
print(f"{key} found in the tree.")
else:
print(f"{key} not found in the tree.")
elif choice == '3':
print("Inorder Traversal:", bst.inorder_traversal())
elif choice == '4':
print("Exiting...")
break
else:
print("Invalid choice. Please enter a valid option.")

if __name__ == "__main__":
main()

You might also like