Here's a comprehensive Python implementation of an AVL (Adelson-Velsky and Landis) tree, which is a self-balancing binary search tree:
class AVLNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1 # Height of the node
class AVLTree:
def __init__(self):
self.root = None
def height(self, node):
"""
Get the height of a node.
Returns 0 if node is None.
"""
if not node:
return 0
return node.height
def balance_factor(self, node):
"""
Calculate the balance factor of a node.
Balance factor = height of left subtree - height of right subtree
"""
if not node:
return 0
return self.height(node.left) - self.height(node.right)
def update_height(self, node):
"""
Update the height of a node based on its children's heights
"""
if not node:
return 0
node.height = 1 + max(self.height(node.left), self.height(node.right))
def right_rotate(self, y):
"""
Perform right rotation
"""
x = y.left
T2 = x.right
# Perform rotation
x.right = y
y.left = T2
# Update heights
self.update_height(y)
self.update_height(x)
return x
def left_rotate(self, x):
"""
Perform left rotation
"""
y = x.right
T2 = y.left
# Perform rotation
y.left = x
x.right = T2
# Update heights
self.update_height(x)
self.update_height(y)
return y
def insert(self, root, key):
"""
Insert a key into the AVL tree
"""
# 1. Perform standard BST insertion
if not root:
return AVLNode(key)
if key < root.key:
root.left = self.insert(root.left, key)
else:
root.right = self.insert(root.right, key)
# 2. Update height of current node
self.update_height(root)
# 3. Get the balance factor
balance = self.balance_factor(root)
# 4. Balance the tree if needed
# Left Left Case
if balance > 1 and key < root.left.key:
return self.right_rotate(root)
# Right Right Case
if balance < -1 and key > root.right.key:
return self.left_rotate(root)
# Left Right Case
if balance > 1 and key > root.left.key:
root.left = self.left_rotate(root.left)
return self.right_rotate(root)
# Right Left Case
if balance < -1 and key < root.right.key:
root.right = self.right_rotate(root.right)
return self.left_rotate(root)
return root
def insert_key(self, key):
"""
Public method to insert a key
"""
self.root = self.insert(self.root, key)
def delete(self, root, key):
"""
Delete a key from the AVL tree
"""
# 1. Perform standard BST deletion
if not root:
return root
if key < root.key:
root.left = self.delete(root.left, key)
elif key > root.key:
root.right = self.delete(root.right, key)
else:
# Node with only one child or no child
if not root.left:
return root.right
elif not root.right:
return root.left
# Node with two children: Get the inorder successor
temp = self.get_min_value_node(root.right)
root.key = temp.key
root.right = self.delete(root.right, temp.key)
# If the tree had only one node, return
if not root:
return root
# 2. Update height of current node
self.update_height(root)
# 3. Get the balance factor
balance = self.balance_factor(root)
# 4. Balance the tree
# Left Left Case
if balance > 1 and self.balance_factor(root.left) >= 0:
return self.right_rotate(root)
# Left Right Case
if balance > 1 and self.balance_factor(root.left) < 0:
root.left = self.left_rotate(root.left)
return self.right_rotate(root)
# Right Right Case
if balance < -1 and self.balance_factor(root.right) <= 0:
return self.left_rotate(root)
# Right Left Case
if balance < -1 and self.balance_factor(root.right) > 0:
root.right = self.right_rotate(root.right)
return self.left_rotate(root)
return root
def delete_key(self, key):
"""
Public method to delete a key
"""
self.root = self.delete(self.root, key)
def get_min_value_node(self, node):
"""
Find the node with minimum value in a given tree
"""
current = node
while current.left:
current = current.left
return current
def inorder_traversal(self, root):
"""
Inorder traversal of the AVL tree
"""
result = []
self._inorder_recursive(root, result)
return result
def _inorder_recursive(self, node, result):
"""
Helper method for inorder traversal
"""
if node:
self._inorder_recursive(node.left, result)
result.append(node.key)
self._inorder_recursive(node.right, result)
def search(self, root, key):
"""
Search for a key in the AVL tree
"""
# Base Cases: root is null or key is present at root
if not root or root.key == key:
return root
# Key is greater than root's key
if root.key < key:
return self.search(root.right, key)
# Key is smaller than root's key
return self.search(root.left, key)
def search_key(self, key):
"""
Public method to search for a key
"""
return self.search(self.root, key)
# Example usage and demonstration
def main():
# Create a new AVL tree
avl_tree = AVLTree()
# Insert some keys
keys_to_insert = [10, 20, 30, 40, 50, 25]
for key in keys_to_insert:
avl_tree.insert_key(key)
# Print inorder traversal
print("Inorder traversal after insertions:")
print(avl_tree.inorder_traversal(avl_tree.root))
# Delete a key
avl_tree.delete_key(30)
# Print inorder traversal after deletion
print("\nInorder traversal after deleting 30:")
print(avl_tree.inorder_traversal(avl_tree.root))
# Search for a key
search_key = 40
result = avl_tree.search_key(search_key)
print(f"\nSearching for {search_key}: {'Found' if result else 'Not Found'}")
# Run the demonstration
if __name__ == "__main__":
main()
This implementation provides a complete AVL tree with the following key features:
Key Methods
-
Insertion (insert):
- Performs standard BST insertion
- Rebalances the tree after insertion
- Handles four rotation cases:
- Left Left (LL)
- Right Right (RR)
- Left Right (LR)
- Right Left (RL)
-
Deletion (delete):
- Performs standard BST deletion
- Handles node removal with 0, 1, or 2 children
- Rebalances the tree after deletion
- Handles the same four rotation cases as insertion
-
Search (search):
- Recursive search for a key in the tree
- Returns the node if found, None otherwise
-
Traversal (inorder_traversal):
- Performs an inorder traversal of the tree
- Returns a list of keys in sorted order
Key Operations
- Height Calculation: O(1)
- Insertion: O(log n)
- Deletion: O(log n)
- Search: O(log n)
Balancing Mechanism
The tree maintains balance through:
- Balance factor calculation
- Height tracking
- Automatic rotations during insertion and deletion
Rotation Types
- Right Rotation: Used when left subtree is too heavy
- Left Rotation: Used when right subtree is too heavy
- Left-Right Rotation: Combination of left and right rotations
- Right-Left Rotation: Combination of right and left rotations
Time Complexity
- Average and Worst Case: O(log n) for all operations
- Space Complexity: O(n)
Example Usage
The main() function demonstrates:
- Tree creation
- Key insertion
- Inorder traversal
- Key deletion
- Key search
Potential Improvements
- Add more error handling
- Implement iterator methods
- Add more traversal methods (preorder, postorder)
- Create methods for tree visualization
Limitations
- Assumes unique keys (no duplicate handling in this implementation)
- Basic implementation without advanced features like range queries
Would you like me to elaborate on any specific aspect of the AVL tree implementation?