class Node:
def __init__(self, key):
[Link] = None
[Link] = None
[Link] = key
# A utility function to insert a new node with the given key
def insert(root, key):
if root is None:
return Node(key)
if [Link] == key:
return root # If the key already exists, do nothing
if [Link] < key:
[Link] = insert([Link], key)
else:
[Link] = insert([Link], key)
return root
# A utility function to search for a given key in the BST
def search(root, key):
# Base cases: root is null or key is present at the root
if root is None:
return False
if [Link] == key:
return True
# Key is greater than root's key
if [Link] < key:
return search([Link], key)
# Key is smaller than root's key
return search([Link], key)
# A utility function to do inorder tree traversal
def inorder(root):
if root:
inorder([Link])
print([Link], end=" ")
inorder([Link])
# A function to find the height of the tree (longest path)
def height(root):
if root is None:
return 0
# Compute the height of each subtree and take the maximum
left_height = height([Link])
right_height = height([Link])
return max(left_height, right_height) + 1
# Take input from the user
n = int(input("Enter the number of elements to insert into the BST: "))
root = None
for _ in range(n):
key = int(input("Enter a key to insert: "))
root = insert(root, key)
# Print inorder traversal of the BST
print("Inorder traversal of the BST:")
inorder(root)
print() # Just to add a newline after the inorder output
# Ask user for a key to search in the BST
search_key = int(input("Enter a key to search in the BST: "))
if search(root, search_key):
print(f"Key {search_key} found in the BST.")
else:
print(f"Key {search_key} not found in the BST.")
# Print the height of the tree (longest path)
print(f"The height (longest path) of the tree is: {height(root)}")