Learn how to implement an efficient recursive search algorithm for Binary Search Trees. Master the technique of leveraging BST properties to optimize search operations.
A Binary Search Tree has these key properties:
Search operation advantages:
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def search(self, value):
return self._search_recursive(self.root, value)
def _search_recursive(self, node, value):
# Base case 1: Empty tree or not found
if node is None:
return None
# Base case 2: Value found
if node.value == value:
return node
# Recursive cases
# Inside _search_recursive after base cases
if value < node.value:
# Search left subtree (smaller values)
return self._search_recursive(node.left, value)
else:
# Search right subtree (larger values)
return self._search_recursive(node.right, value)
class BST:
def __init__(self):
self.root = None
def search(self, value):
return self._search_recursive(self.root, value)
def _search_recursive(self, node, value):
# Base case 1: Empty tree or not found
if node is None:
return None
# Base case 2: Value found
if node.value == value:
return node
# Recursive cases
if value < node.value:
# Search left subtree (smaller values)
return self._search_recursive(node.left, value)
else:
# Search right subtree (larger values)
return self._search_recursive(node.right, value)
Now that you've learned how to implement a recursive search in a Binary Search Tree, try these challenges to reinforce your understanding.
Implement two methods to find the minimum and maximum values in a BST.
findMin()
to find the minimum value in the BSTfindMax()
to find the maximum value in the BSTclass BST:
# ... existing implementation
def find_min(self):
# Your code here
pass
def _find_min_recursive(self, node):
# Your code here
pass
def find_max(self):
# Your code here
pass
def _find_max_recursive(self, node):
# Your code here
pass
Implement a method that counts how many nodes have values in a given range [min, max].
countNodesInRange(min, max)
that returns the count of nodes
with values between min and max (inclusive)class BST:
# ... existing implementation
def count_nodes_in_range(self, min_value, max_value):
return self._count_nodes_in_range_recursive(self.root, min_value, max_value)
def _count_nodes_in_range_recursive(self, node, min_value, max_value):
# Your code here
pass
If you want more practice with BST operations, check out these LeetCode problems: