The document contains a Python implementation of a Binary Search Tree (BST) with functions for inserting nodes, searching for keys, performing inorder traversal, and calculating the height of the tree. It prompts the user to input elements to insert into the BST and allows searching for a specific key. Finally, it outputs the inorder traversal and the height of the tree.
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 ratings0% found this document useful (0 votes)
2 views
BST Code with operations.
The document contains a Python implementation of a Binary Search Tree (BST) with functions for inserting nodes, searching for keys, performing inorder traversal, and calculating the height of the tree. It prompts the user to input elements to insert into the BST and allows searching for a specific key. Finally, it outputs the inorder traversal and the height of the tree.
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 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 the key already exists, do nothing if root.val < key: root.right = insert(root.right, key) else: root.left = insert(root.left, 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 root.val == key: return True # Key is greater than root's key if root.val < key: return search(root.right, key) # Key is smaller than root's key return search(root.left, key)
# A utility function to do inorder tree traversal
def inorder(root): if root: inorder(root.left) print(root.val, end=" ") inorder(root.right)
# 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(root.left) right_height = height(root.right) 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)}")