write the code for a self balancing tree in python that supports the following operations all in O(log(n)) time:
inserting a number
removing a number
returning the amount of numbers less than or equal to some number x (x can be different for different queries)
returning the amount of numbers greater than or equal to some number x (x can be different for different queries)
Assistant
Certainly! Below is a Python implementation of a self-balancing AVL tree that supports the following operations in ( O(\log n) ) time:
Inserting a number
Removing a number
Returning the amount of numbers less than or equal to some number ( x )
Returning the amount of numbers greater than or equal to some number ( x )
Overview
To achieve the required time complexities, the AVL tree is augmented with additional information:
Height: To maintain the balance of the tree.
Size: The total number of nodes (including duplicates) in the subtree rooted at a particular node. This helps in efficiently computing ranks (counts of elements ≤ or ≥ a given value).
Count: To handle duplicate keys by keeping a count of how many times a particular key has been inserted.
Implementation Details
Insertion (insert): Insert the key into the tree. If the key already exists, increment its count. After insertion, update the height and size of the nodes and rebalance the tree if necessary.
Deletion (remove): Remove a key from the tree. If the key's count is greater than one, simply decrement the count. Otherwise, remove the node from the tree and rebalance.
Count Less Than or Equal (count_less_than_or_equal): Traverse the tree and accumulate the counts of nodes with keys less than or equal to ( x ).
Count Greater Than or Equal (count_greater_than_or_equal): Similar to the above but accumulates counts of nodes with keys greater than or equal to ( x ).
Complete Code
python
class AVLTreeNode:
def __init__(self, key):
self.key = key
self.count = 1 # Number of times this key is present
self.left = None
self.right = None
self.height = 1 # Height of this node in the tree
self.size = 1 # Total number of nodes in the subtree rooted here, including duplicates
class AVLTree:
def __init__(self):
self.root = None
# Helper function to get height of a node
def get_height(self, node):
return node.height if node else 0
# Helper function to get size of a node
def get_size(self, node):
return node.size if node else 0
# Update height and size of a node
def update_node(self, node):
node.height = 1 + max(self.get_height(node.left), self.get_height(node.right))
node.size = node.count + self.get_size(node.left) + self.get_size(node.right)
# Get balance factor of a node
def get_balance(self, node):
if not node:
return 0
return self.get_height(node.left) - self.get_height(node.right)
# Right rotate
def right_rotate(self, y):
x = y.left
T2 = x.right
# Perform rotation
x.right = y
y.left = T2
# Update heights and sizes
self.update_node(y)
self.update_node(x)
return x
# Left rotate
def left_rotate(self, x):
y = x.right
T2 = y.left
# Perform rotation
y.left = x
x.right = T2
# Update heights and sizes
self.update_node(x)
self.update_node(y)
return y
# Insert a key into the subtree rooted at node
def _insert(self, node, key):
if not node:
return AVLTreeNode(key)
if key < node.key:
node.left = self._insert(node.left, key)
elif key > node.key:
node.right = self._insert(node.right, key)
else:
node.count += 1
node.size += 1
return node
self.update_node(node)
balance = self.get_balance(node)
# Left Left Case
if balance > 1 and key < node.left.key:
return self.right_rotate(node)
# Right Right Case
if balance < -1 and key > node.right.key:
return self.left_rotate(node)
# Left Right Case
if balance > 1 and key > node.left.key:
node.left = self.left_rotate(node.left)
return self.right_rotate(node)
# Right Left Case
if balance < -1 and key < node.right.key:
node.right = self.right_rotate(node.right)
return self.left_rotate(node)
return node
def insert(self, key):
self.root = self._insert(self.root, key)
# Find the node with minimum key value
def min_value_node(self, node):
current = node
while current.left:
current = current.left
return current
# Remove a key from the subtree rooted at node
def _remove(self, node, key):
if not node:
return node
if key < node.key:
node.left = self._remove(node.left, key)
elif key > node.key:
node.right = self._remove(node.right, key)
else:
if node.count > 1:
node.count -= 1
node.size -= 1
return node
else:
if not node.left:
temp = node.right
node = None
return temp
elif not node.right:
temp = node.left
node = None
return temp
temp = self.min_value_node(node.right)
node.key = temp.key
node.count = temp.count
temp.count = 1
node.right = self._remove(node.right, temp.key)
if not node:
return node
self.update_node(node)
balance = self.get_balance(node)
# Left Left Case
if balance > 1 and self.get_balance(node.left) >= 0:
return self.right_rotate(node)
# Left Right Case
if balance > 1 and self.get_balance(node.left) < 0:
node.left = self.left_rotate(node.left)
return self.right_rotate(node)
# Right Right Case
if balance < -1 and self.get_balance(node.right) <= 0:
return self.left_rotate(node)
# Right Left Case
if balance < -1 and self.get_balance(node.right) > 0:
node.right = self.right_rotate(node.right)
return self.left_rotate(node)
return node
def remove(self, key):
self.root = self._remove(self.root, key)
# Count number of keys <= x
def count_less_than_or_equal(self, x):
return self._count_less_than_or_equal(self.root, x)
def _count_less_than_or_equal(self, node, x):
if not node:
return 0
if node.key == x:
return self.get_size(node.left) + node.count
elif node.key < x:
return self.get_size(node.left) + node.count + self._count_less_than_or_equal(node.right, x)
else:
return self._count_less_than_or_equal(node.left, x)
# Count number of keys >= x
def count_greater_than_or_equal(self, x):
return self._count_greater_than_or_equal(self.root, x)
def _count_greater_than_or_equal(self, node, x):
if not node:
return 0
if node.key == x:
return self.get_size(node.right) + node.count
elif node.key > x:
return self.get_size(node.right) + node.count + self._count_greater_than_or_equal(node.left, x)
else:
return self._count_greater_than_or_equal(node.right, x)
# Optional: In-order traversal (for testing)
def inorder(self):
res = []
self._inorder(self.root, res)
return res
def _inorder(self, node, res):
if not node:
return
self._inorder(node.left, res)
res.extend([node.key] * node.count)
self._inorder(node.right, res)
# Example Usage:
if __name__ == "__main__":
tree = AVLTree()
elements = [20, 4, 15, 70, 50, 100, 100, 4]
for el in elements:
tree.insert(el)
print("In-order traversal:", tree.inorder())
print("Count <= 15:", tree.count_less_than_or_equal(15)) # Expected: 4
print("Count >= 50:", tree.count_greater_than_or_equal(50)) # Expected: 4
tree.remove(4)
print("After removing one '4':", tree.inorder())
print("Count <= 15:", tree.count_less_than_or_equal(15)) # Expected: 3
tree.remove(100)
print("After removing one '100':", tree.inorder())
print("Count >= 50:", tree.count_greater_than_or_equal(50)) # Expected: 3
Explanation
Node Structure (AVLTreeNode):
key: The value stored in the node.
count: Number of occurrences of key.
left & right: Pointers to the left and right children.
height: Height of the node in the tree, used for balancing.
size: Total number of nodes in the subtree rooted at this node (including duplicates). This is crucial for efficiently computing the rank of elements.
AVL Tree Operations (AVLTree):
Insertion (insert): Inserts a key while maintaining the AVL balance. If the key already exists, it increments the count and updates the size.
Deletion (remove): Removes a key. If multiple instances of the key exist, it decrements the count. Otherwise, it removes the node and rebalances the tree.
Counting Less Than or Equal (count_less_than_or_equal): Traverses the tree to count all nodes with keys ≤ ( x ) by utilizing the size attribute.
Counting Greater Than or Equal (count_greater_than_or_equal): Similar to the above but counts nodes with keys ≥ ( x ).
Traversal (inorder): Provides an in-order traversal of the tree, useful for testing and verification.
Example Usage:
Inserts a series of numbers into the AVL tree, including duplicates.
Demonstrates how to use the count operations.
Shows the state of the tree after some deletions.
Notes
Handling Duplicates: The tree efficiently handles duplicate keys by maintaining a count at each node. The size attribute ensures that the ranks are correctly computed even with duplicates.
Balancing: The AVL tree ensures that all operations remain ( O(\log n) ) by maintaining the tree's balance after every insertion and deletion through rotations.
Customization: You can extend this implementation to include additional functionalities as needed, such as finding the ( k )-th smallest element, etc.
This implementation should serve as a robust foundation for managing a dynamic set of numbers with efficient query capabilities.