Create a binary search tree and implement insertion and search operations.
- User
Create a binary search tree and implement insertion and search operations.
Assistant
Create a binary search tree and implement insertion and search operations.
1. Understand the Goal: The user wants a binary search tree (BST) implementation with two main operations: insertion and search. The response should be code-based, likely in a popular language like Python, Java, or C++. I should probably provide a Python example as it's most accessible for algorithmic concepts, but maybe C++ or Java are also good for showing structure. I'll stick to Python for clarity, but I'll write it in a way that's easily translatable.
Core Concepts of a BST:
Drafting the Code Structure (Python):
Class Node:
__init__(self, value): Initialize val, left (None), right (None).Class BinarySearchTree:
__init__(self): Initialize root (None).
Insert Method:
_insert_recursive(current, value):
current is None: return Node(value).value < current.val: current.left = _insert_recursive(current.left, value).value > current.val: current.right = _insert_recursive(current.right, value).current.insert(value): self.root = _insert_recursive(self.root, value).Search Method:
_search_recursive(current, value):
current is None: return False.value == current.val: return True.value < current.val: return _search_recursive(current.left, value)._search_recursive(current.right, value).search(value): return _search_recursive(self.root, value).In-order Traversal (Optional but good for verification):
Refining the Implementation:
Adding Explanations:
Review against common pitfalls:
self.root = ....Final Code Assembly (Mental Check):
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert(self, key):
# Logic
pass
def search(self, key):
# Logic
pass
Formatting the Output:
Self-Correction during drafting:
insert calls a recursive helper, or just implement the recursive logic directly if the API supports passing nodes (but usually APIs don't expose nodes). So insert(val) -> _insert(node, val).Final Polish: Ensure clear comments in the code.
(Self-Correction for the prompt language): The prompt is in English. I will respond in English.
Let's write the solution. Here is a complete implementation of a Binary Search Tree (BST) in Python.
This implementation includes:
Node class to represent individual elements.BinarySearchTree class with methods for Insertion and Search.class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
# --- INSERTION OPERATION ---
def insert(self, value):
if self.root is None:
self.root = Node(value)
return
current = self.root
while True:
if value < current.value:
# Go left
if current.left is None:
current.left = Node(value)
return
current = current.left
elif value > current.value:
# Go right
if current.right is None:
current.right = Node(value)
return
current = current.right
else:
# Value already exists (duplicate)
return
# --- SEARCH OPERATION ---
def search(self, value):
current = self.root
while current is not None:
if value == current.value:
return True # Found
elif value < current.value:
current = current.left # Go left
else:
current = current.right # Go right
return False # Not found
# --- HELPER: In-order Traversal (Left, Root, Right) ---
# This prints the values in sorted order to verify the structure.
def inorder_traversal(self, node, result=None):
if result is None:
result = []
if node:
self.inorder_traversal(node.left, result)
result.append(node.value)
self.inorder_traversal(node.right, result)
return result
# --- Usage Example ---
# 1. Create the tree
bst = BinarySearchTree()
# 2. Insert values
# Tree structure visualization after inserts:
# 10
# / \
# 5 15
# / \ \
# 2 7 20
print("Inserting values: 10, 5, 15, 2, 7, 20")
bst.insert(10)
bst.insert(5)
bst.insert(15)
bst.insert(2)
bst.insert(7)
bst.insert(20)
# 3. Verify structure (Should print sorted: 2, 5, 7, 10, 15, 20)
print("Sorted Tree:", bst.inorder_traversal(bst.root))
# 4. Search operations
print("\nSearching for 7:", bst.search(7)) # Should be True
print("Searching for 100:", bst.search(100)) # Should be False
print("Searching for 2:", bst.search(2)) # Should be True
The Node Class:
value.left and right children (initially None).Insertion Logic:
None) and place the new node there.Search Logic:
True.None (a dead end), the value does not exist in the tree, so we return False.1, 2, 3, 4, 5 into an empty tree, everything just goes to the right, creating a straight line.