When a node is accessed, a splay operation is performed on
to move it to the root. To perform a splay operation we carry out a sequence of splay steps, each of which moves
closer to the root. By performing a splay operation on the node of interest after every access, the recently accessed nodes are kept near the root and the tree remains roughly balanced, so that we achieve the desired amortized time bounds.
Each particular step depends on three factors:
It is important to remember to set (the great-grandparent of
) to now point to
after any splay operation. If
is null, then
obviously is now the root and must be updated as such.
There are three types of splay steps, each of which has a left- and right-handed case. For the sake of brevity, only one of these two is shown for each type. These three types are:
Zig step: This step is done when is the root. The tree is rotated on the edge between
and
. Zig steps exist to deal with the parity issue and will be done only as the last step in a splay operation and only when
has odd depth at the beginning of the operation (see fig.
).
Zig-zig step: This step is done when is not the root and
and
are either both right children or are both left children. The picture below shows the case where
and
are both left children. The tree is rotated on the edge joining
with its parent
, then rotated on the edge joining
with
. Note that zig-zig steps are the only thing that differentiate splay trees from the rotate to root method introduced by Allen and Munro prior to the introduction of splay trees (see fig.
).
Zig-zag step: This step is done when is not the root and
is a right child and
is a left child or vice versa. The tree is rotated on the edge between
and
, and then rotated on the resulting edge between
and
.
Join. Given two trees and
such that all elements of
are smaller than the elements of
, the following steps can be used to join them to a single tree:
Split. Given a tree and an element , return two new trees: one containing all elements less than or equal to
and the other containing all elements greater than
. This can be done in the following way:
Insertion. To insert a value into a splay tree:
Deletion. To delete a node , use the same method as with a binary search tree: if
has two children, swap its value with that of either the rightmost node of its left sub tree (its in-order predecessor) or the leftmost node of its right subtree (its in-order successor). Then remove that node instead. In this way, deletion is reduced to the problem of removing a node with 0 or
children. Unlike a binary search tree, in a splay tree after deletion, we splay the parent of the removed node to the top of the tree.