0% found this document useful (0 votes)
8 views1 page

Code by Sarvesh

The document defines a binary search tree (BST) implementation in Python, including a Node class and functions for inserting nodes and performing inorder traversal. It prompts the user to input the number of elements and their respective keys to be inserted into the BST. Finally, it prints the inorder traversal of the constructed BST.

Uploaded by

rosiriw830
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)
8 views1 page

Code by Sarvesh

The document defines a binary search tree (BST) implementation in Python, including a Node class and functions for inserting nodes and performing inorder traversal. It prompts the user to input the number of elements and their respective keys to be inserted into the BST. Finally, it prints the inorder traversal of the constructed BST.

Uploaded by

rosiriw830
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/ 1

class Node:

def __init__(self, key):


self.left = None
self.right = None
self.val = 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 root.val == key:
return root
if root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root
# A utility function to do inorder tree traversal
def inorder(root):
if root:
inorder(root.left)
print(root.val, end=" ")
inorder(root.right)
# 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)

You might also like