class Node:
def __init__(self, key, value=None):
self.key = key
self.value = value
self.left = None
self.right = None
self.parent = None
self.freq = 0 # Access frequency counter
class SplayTree:
def __init__(self):
self.root = None
def rotate_right(self, x):
y = x.left
x.left = y.right
if y.right:
y.right.parent = x
y.parent = x.parent
if x.parent:
if x.parent.left == x:
x.parent.left = y
else:
x.parent.right = y
y.right = x
x.parent = y
return y
def rotate_left(self, x):
y = x.right
x.right = y.left
if y.left:
y.left.parent = x
y.parent = x.parent
if x.parent:
if x.parent.left == x:
x.parent.left = y
else:
x.parent.right = y
y.left = x
x.parent = y
return y
def splay(self, node):
if not node:
return
while node.parent:
parent = node.parent
grand = parent.parent
if not grand:
# Zig
if node == parent.left:
self.rotate_right(parent)
else:
self.rotate_left(parent)
elif (node == parent.left and parent == grand.left) or \
(node == parent.right and parent == grand.right):
# Zig-zig
if node == parent.left:
self.rotate_right(grand)
self.rotate_right(parent)
else:
self.rotate_left(grand)
self.rotate_left(parent)
else:
# Zig-zag
if node == parent.left:
self.rotate_right(parent)
else:
self.rotate_left(parent)
# Second rotate
parent = node.parent
if node == parent.left:
self.rotate_right(parent)
else:
self.rotate_left(parent)
self.root = node
def _find_node(self, key):
"""BST find without splaying or incrementing freq."""
curr = self.root
while curr:
if key == curr.key:
return curr
elif key < curr.key:
curr = curr.left
else:
curr = curr.right
return None
def find(self, key):
"""Find value for key, increment freq on hit, splay on hit or miss (splays last node)."""
if not self.root:
return None
curr = self.root
last = None
while curr:
if key == curr.key:
curr.freq += 1
self.splay(curr)
return curr.value
last = curr
if key < curr.key:
curr = curr.left
else:
curr = curr.right
# Miss: splay the last node (insertion point)
if last:
self.splay(last)
return None
def insert(self, key, value):
"""Insert or update key-value, increment freq, splay new/existing node."""
if self.root is None:
self.root = Node(key, value)
self.root.freq = 1
return
curr = self.root
parent = None
while curr:
parent = curr
if key == curr.key:
curr.value = value
curr.freq += 1
self.splay(curr)
return
elif key < curr.key:
curr = curr.left
else:
curr = curr.right
# Insert new node
new_node = Node(key, value)
new_node.freq = 1
new_node.parent = parent
if key < parent.key:
parent.left = new_node
else:
parent.right = new_node
self.splay(new_node)
def delete(self, key):
"""Delete key if exists, increment freq before delete, splay it first."""
node = self._find_node(key)
if not node:
return
node.freq += 1
self.splay(node) # Now node is root
left = self.root.left
right = self.root.right
if left:
left.parent = None
if right:
right.parent = None
if left is None:
self.root = right
elif right is None:
self.root = left
else:
# Find rightmost (max) in left
rm = left
while rm.right:
rm = rm.right
# Attach right to rm
rm.right = right
if right:
right.parent = rm
# Set temp root and splay rm
self.root = left
self.splay(rm)
def get_freq(self, key):
"""Get access frequency of key without modifying tree."""
node = self._find_node(key)
return node.freq if node else 0
def __str__(self):
"""Inorder traversal for debug."""
def inorder(node):
if not node:
return []
return inorder(node.left) + [(node.key, node.value, node.freq)] + inorder(node.right)
if not self.root:
return "Empty"
return str(inorder(self.root))
Explanation
- Splay Tree Core: Implements standard bottom-up splaying with zig, zig-zig, and zig-zag rotations using parent pointers. Every access (find hit/miss, insert, delete) splays the relevant node(s) to the root for amortized O(log n) performance.
- Access Frequency Optimization:
- Each
Node tracks freq, incremented on every successful access (find hit, insert/update, delete).
- Splaying ensures frequently accessed nodes are moved to the root, optimizing future accesses to high-frequency keys (recency + repeated access keeps them near root).
- On unsuccessful finds, splays the last node on the search path (insertion point), preparing for potential future inserts there.
- Operations:
find(key): Returns value or None, optimizes path.
insert(key, value): Upserts, always splays.
delete(key): Splays then merges subtrees efficiently by attaching to predecessor.
get_freq(key): Query freq without side effects.
- Usage Example:
st = SplayTree()
st.insert(10, "ten")
st.insert(20, "twenty")
print(st.find(10)) # "ten", freq[10]=1
print(st.get_freq(10)) # 1
print(st) # [(10, 'ten', 1), (20, 'twenty', 0)]
st.find(10) # Access again, splays 10 to root, freq=2
st.delete(20)
This implementation provides self-adjustment optimized for access patterns, where high-frequency keys enjoy near-constant time after repeated access.