Write code for bst
- User
Write code for bst
- Assistant
Write code for bst
Certainly! A Binary Search Tree (BST) is a data structure that facilitates fast lookup, addition, and deletion of items. Each node in the BST contains a value, and all values in the left subtree are less than the node's value, while all values in the right subtree are greater.
Below is a Python implementation of a BST with common operations such as insertion, search, and in-order traversal.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, key):
"""Insert a key into the BST."""
if self.root is None:
self.root = Node(key)
print(f"Inserted root node: {key}")
else:
self._insert_recursive(self.root, key)
def _insert_recursive(self, current_node, key):
if key < current_node.key:
if current_node.left is None:
current_node.left = Node(key)
print(f"Inserted {key} to the left of {current_node.key}")
else:
self._insert_recursive(current_node.left, key)
elif key > current_node.key:
if current_node.right is None:
current_node.right = Node(key)
print(f"Inserted {key} to the right of {current_node.key}")
else:
self._insert_recursive(current_node.right, key)
else:
print(f"Key {key} already exists in the BST.")
def search(self, key):
"""Search for a key in the BST. Returns True if found, else False."""
return self._search_recursive(self.root, key)
def _search_recursive(self, current_node, key):
if current_node is None:
print(f"Key {key} not found.")
return False
if key == current_node.key:
print(f"Key {key} found.")
return True
elif key < current_node.key:
return self._search_recursive(current_node.left, key)
else:
return self._search_recursive(current_node.right, key)
def inorder_traversal(self):
"""Perform in-order traversal of the BST."""
elements = []
self._inorder_recursive(self.root, elements)
return elements
def _inorder_recursive(self, current_node, elements):
if current_node:
self._inorder_recursive(current_node.left, elements)
elements.append(current_node.key)
self._inorder_recursive(current_node.right, elements)
def delete(self, key):
"""Delete a key from the BST."""
self.root, deleted = self._delete_recursive(self.root, key)
if deleted:
print(f"Key {key} has been deleted.")
else:
print(f"Key {key} not found in the BST.")
def _delete_recursive(self, current_node, key):
if current_node is None:
return current_node, False
deleted = False
if key == current_node.key:
deleted = True
# Node with only one child or no child
if current_node.left is None:
return current_node.right, deleted
elif current_node.right is None:
return current_node.left, deleted
# Node with two children: Get the inorder successor
temp = self._min_value_node(current_node.right)
current_node.key = temp.key
current_node.right, _ = self._delete_recursive(current_node.right, temp.key)
elif key < current_node.key:
current_node.left, deleted = self._delete_recursive(current_node.left, key)
else:
current_node.right, deleted = self._delete_recursive(current_node.right, key)
return current_node, deleted
def _min_value_node(self, node):
"""Get the node with the smallest key greater than the current node."""
current = node
while current.left is not None:
current = current.left
return current
# Example Usage
if __name__ == "__main__":
bst = BinarySearchTree()
# Insert elements
bst.insert(50)
bst.insert(30)
bst.insert(70)
bst.insert(20)
bst.insert(40)
bst.insert(60)
bst.insert(80)
# In-order Traversal
print("In-order Traversal:", bst.inorder_traversal())
# Search for elements
bst.search(40) # Found
bst.search(25) # Not found
# Delete elements
bst.delete(20) # Deleting a leaf node
bst.delete(30) # Deleting a node with one child
bst.delete(50) # Deleting a node with two children
# In-order Traversal after deletions
print("In-order Traversal after deletions:", bst.inorder_traversal())
Node Class: Represents each node in the BST, containing a key, and pointers to the left and right child nodes.
BinarySearchTree Class:
__init__: Initializes an empty BST.insert: Inserts a new key into the BST. It checks if the tree is empty and inserts the root node if so. Otherwise, it calls the _insert_recursive helper method to find the appropriate position._insert_recursive: Recursively finds the correct position to insert the new key based on BST properties.search: Searches for a key in the BST. Returns True if found, else False._search_recursive: Helper method to perform recursive search.inorder_traversal: Performs an in-order traversal of the BST, which returns the elements in sorted order._inorder_recursive: Helper method for in-order traversal.delete: Deletes a key from the BST if it exists._delete_recursive: Helper method to handle deletion, considering different cases (no child, one child, two children)._min_value_node: Finds the node with the smallest key in a subtree, used to find the in-order successor during deletion.Example Usage:
Inserted root node: 50
Inserted 30 to the left of 50
Inserted 70 to the right of 50
Inserted 20 to the left of 30
Inserted 40 to the right of 30
Inserted 60 to the left of 70
Inserted 80 to the right of 70
In-order Traversal: [20, 30, 40, 50, 60, 70, 80]
Key 40 found.
Key 25 not found.
Key 20 has been deleted.
Key 30 has been deleted.
Key 50 has been deleted.
In-order Traversal after deletions: [40, 60, 70, 80]
Depending on your requirements, you might want to implement additional operations such as:
If you need implementations for these or have any other specific requirements, feel free to ask!
Not yet included in a published release.