Splay Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/seayoungsjtu/article/details/49977953

Based on“Data Structures and Algorithm Analysis Edition 3.2 (C++ Version)” from C. A. Shaffer

Proporities

  • A splay tree is a self-adjusting binary search tree with the additional property that recently accessed elements are quick to access again. To implement this, all normal operations on a binary search tree are combined with one basic operation, called splaying.
  • Having frequently used nodes near the root is an advantage for nearly all practical applications, and is particularly useful for implementing caches and garbage collection algorithms.
  • The most significant disadvantage of splay trees is that the height of a splay tree can be linear. Besides, the representation of splay trees can change even when they are accessed in a ‘read-only’ manner (i.e. by find operations). This complicates the use of such splay trees in a multi-threaded environment.

Operations

Splay

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:
1. Zig Step: This step is done when p is the root. The tree is rotated on the edge between x and p. 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 x has odd depth at the beginning of the operation.
这里写图片描述
2. Zig-zig Step: This step is done when p is not the root and x and p are either both right children or are both left children. The picture below shows the case where x and p are both left children. The tree is rotated on the edge joining p with its parent g, then rotated on the edge joining x with p. 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.
这里写图片描述
3. Zig-zag Step: This step is done when p is not the root and x is a right child and p is a left child or vice versa. The tree is rotated on the edge between p and x, and then rotated on the resulting edge between x and g.
这里写图片描述

Insert

To insert a node x into a splay tree:
- First insert the node as with a normal BST;
- Then splay the newly inserted node x to the top of the tree.

Remove

The first step of removing a node is just the same as removing a node in a BST; After deletion, we splay the parent of the removed node to the top of the tree, OR The node to be deleted is first splayed.

猜你喜欢

转载自blog.csdn.net/seayoungsjtu/article/details/49977953