Welcome to a deep dive into Splay Trees! In this lesson, we'll cover the fundamentals of Splay Trees, a self-balancing binary search tree, and understand why they are important for practical applications.
Splay Trees are a type of self-balancing binary search tree, invented by Daniel Sleator and Robert Tarjan. They are designed to minimize the average time complexity of operations like search, insert, and delete, making them highly efficient in many real-world scenarios.
Splay Trees offer several advantages over other data structures like AVL Trees and Red-Black Trees. For instance, Splay Trees do not require constant height maintenance, making them simpler to implement. Additionally, Splay Trees perform better in certain scenarios, such as when there are many frequent insertions, deletions, or searches in random order.
There are four basic Splay Tree operations that rotate the tree to minimize its height:
Left Rotation (Zig Operation)
Right Rotation (Zag Operation)
Double Rotation
Splay Operation
Let's take a look at a simple example of a Splay Tree.
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.left = None
self.right = None
self.size = 1
def get_size(self):
return self.size
def insert(self, key, value):
if self.key is None:
self.key = key
self.value = value
self.size = 1
else:
if self.key < key:
if self.right is None:
self.right = Node(key, value)
else:
self.right.splay(key, value)
else:
if self.left is None:
self.left = Node(key, value)
else:
self.left.splay(key, value)
# Splay Tree Operations are not shown here for brevity
What is the time complexity of the search operation in a Splay Tree in the average case?
What does a Splay Tree do to minimize its height after an insert or delete operation?