文章目錄
1、伸展樹簡介
伸展樹(Splay Tree)是特殊的二叉查找樹(BST)。
它的特殊是指,它除了本身是棵二叉查找樹之外,它還具備一個特點: 當某個節點被訪問時,伸展樹會通過旋轉使該節點成爲樹根。這樣做的好處是,下次要訪問該節點時,能夠迅速的訪問到該節點。
通過之前的學習,知道連續m次查找,對於AVL樹來說,共需要O(mlogn)時間。根據局部性原理,我們可以改進AVL樹!!-----> 引入伸展樹
局部性:剛被訪問過的數據,極有可能很快地再次被訪問。下一將要訪問的節點,極有可能就在剛被訪問過的節點附近。
1.2、特性
1.和普通的二叉查找樹相比,具有任何情況下、任何操作的平攤O(log2n)的複雜度,時間性能上更好
2.和一般的平衡二叉樹比如 紅黑樹、AVL樹相比,維護更少的節點額外信息,空間性能更優,同時編程複雜度更低
3.在很多情況下,對於查找操作,後面的查詢和之前的查詢有很大的相關性。這樣每次查詢操作將被查到的節點旋轉到樹的根節點位置,這樣下次查詢操作可以很快的完成
4.可以完成對區間的查詢、修改、刪除等操作,可以實現線段樹和樹狀數組的所有功能
2、 性能評價
無需記錄節點高度或者平衡因子,編程簡單——優於AVL樹
分攤複雜度O(logN) —— 與AVL樹相當
局部性強、緩存命中率極高時(即k<<n<<n)
效率甚至可以更高——自適應的O(logK)
任何連續的m次查找,都可在O(mlogk + nlogn)時間內完成
但是
仍不能保證單詞最壞情況的出現
不適用於對效率敏感的場所
3、逐層伸展( X )
伸展方式有兩種:1 逐層伸展 2雙層伸展
逐層伸展:一步一步往上,自下而上,逐層單旋。直到V最終被推送至根。
但效率很低,最壞情況:對於下圖依次訪問1~7的話,每一週期總時間O(n^2),分攤時間O(n)。遠小於AVL樹的O(logN)
Zig-zig / zag-zag 的逐層旋轉:
4、雙層伸展 ( √ )
雙層伸展:向上追溯兩層,而非一層! (Tarjan提出)
實現O(log2n)量級的平攤複雜度依靠每次對伸展樹進行查詢、修改、刪除操作之後,都進行旋轉操作 Splay(x, root),該操作將節點x旋轉到樹的根部。
優點:① 摺疊效果:一旦訪問壞節點,對應路徑的長度將隨機減半
② 最好情況不會持續發生,單趟伸展操作,分攤O(logN)
時間
伸展樹的旋轉有六種類型,如果去掉鏡像的重複,則爲三種:
zig(zag)、zig-zig(zag-zag)、zig-zag(zag-zig)。
4.1 zig- zig 旋轉
如下圖所示。在逐層伸展方式中,先VP旋轉,再VG旋轉。在雙層旋轉中,先對祖父節點G進行PG的越級旋轉,再進行VP的旋轉!!!(和第3部分的圖對比一下區別)
優點:在一棵退化成單鏈的伸展樹中訪問其最深的節點,經過伸展後樹高大約爲原先的1/2
4.2 zig- zag 旋轉
如下圖所示,VPG三者在之字型鏈上。此時,先對P節點進行PV的zig旋轉,再對G節點進行GV的zag旋轉,最後變爲右圖所示,V成爲P和G的祖先節點。這個方法和AVL樹雙旋完全等效,與逐層伸展別無二致。
4.3 zig / zag 旋轉
如果V只有父親,沒有祖父。就會出現下圖所示。Parent(v) = root(T) 在每輪調整中,這種情況至多(在最後)出現一次。
5、節點
public class mySplayTree<AnyType extends Comparable<? super AnyType>>
{
/**
* Construct the tree.
*/
public mySplayTree( )
{
nullNode = new BinaryNode<AnyType>( null );
nullNode.left = nullNode.right = nullNode;
root = nullNode;
}
private BinaryNode<AnyType> newNode = null; // Used between different inserts
private BinaryNode<AnyType> header = new BinaryNode<AnyType>( null );
private BinaryNode<AnyType> root;
private BinaryNode<AnyType> nullNode;
}
6、查找
不論成功與否,總會把最後被訪問的節點伸展到根。 —> 動態操作(回想一下之前學的二叉樹、BVL樹的查找都是靜態操作噢)
private BinaryNode<AnyType> splay( AnyType x, BinaryNode<AnyType> t )
{
BinaryNode<AnyType> leftTreeMax, rightTreeMin;
header.left = header.right = nullNode;
leftTreeMax = rightTreeMin = header;
nullNode.element = x; // Guarantee a match
for( ; ; )
{
int compareResult = x.compareTo( t.element );
if( compareResult < 0 )
{
if( x.compareTo( t.left.element ) < 0 )
t = rotateWithLeftChild( t );
if( t.left == nullNode )
break;
// Link Right
rightTreeMin.left = t;
rightTreeMin = t;
t = t.left;
}
else if( compareResult > 0 )
{
if( x.compareTo( t.right.element ) > 0 )
t = rotateWithRightChild( t );
if( t.right == nullNode )
break;
// Link Left
leftTreeMax.right = t;
leftTreeMax = t;
t = t.right;
}
else
break;
}
leftTreeMax.right = t.left;
rightTreeMin.left = t.right;
t.left = header.right;
t.right = header.left;
return t;
}
public AnyType findMin( )
{
BinaryNode<AnyType> ptr = root;
while( ptr.left != nullNode )
ptr = ptr.left;
root = splay( ptr.element, root );
return ptr.element;
}
public AnyType findMax( )
{
BinaryNode<AnyType> ptr = root;
while( ptr.right != nullNode )
ptr = ptr.right;
root = splay( ptr.element, root );
return ptr.element;
}
7、插入
最直觀的思路:調用BST標準的插入算法,再將新節點伸展到根。但是,其中要調用BST.search()方法,而Splay.search()集成了splay()操作,查找失敗後,小於key的最後一個節點會被伸展到根,所以只用在此處插入即可。
如果要插入的節點V,首先調用Splay.search() 它將查找失敗、並把t伸展到根節點;只需把v插入成t的父節點。
public void insert( AnyType x )
{
if( newNode == null )
newNode = new BinaryNode<AnyType>( null );
newNode.element = x;
if( root == nullNode )
{
newNode.left = newNode.right = nullNode;
root = newNode;
}
else
{
root = splay( x, root );
int compareResult = x.compareTo( root.element );
if( compareResult < 0 )
{
newNode.left = root.left;
newNode.right = root;
root.left = nullNode;
root = newNode;
}
else
if( compareResult > 0 )
{
newNode.right = root.right;
newNode.left = root;
root.right = nullNode;
root = newNode;
}
else
return; // No duplicates
}
newNode = null; // So next insert will call new
}
8、刪除
public void remove( AnyType x )
{
if( !contains( x ) )
return;
BinaryNode<AnyType> newTree;
// If x is found, it will be splayed to the root by contains
if( root.left == nullNode )
newTree = root.right;
else
{
// Find the maximum in the left subtree
// Splay it to the root; and then attach right child
newTree = root.left;
newTree = splay( x, newTree );
newTree.right = root.right;
}
root = newTree;
}
9、代碼實現
// SplayTree class
//
// CONSTRUCTION: with no initializer
//
// ******************PUBLIC OPERATIONS*********************
// void insert( x ) --> Insert x
// void remove( x ) --> Remove x
// boolean contains( x ) --> Return true if x is found
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// ******************ERRORS********************************
// Throws UnderflowException as appropriate
/**
* Implements a top-down splay tree.
* Note that all "matching" is based on the compareTo method.
* @author Mark Allen Weiss
*/
public class mySplayTree<AnyType extends Comparable<? super AnyType>>
{
/**
* Construct the tree.
*/
public mySplayTree( )
{
nullNode = new BinaryNode<AnyType>( null );
nullNode.left = nullNode.right = nullNode;
root = nullNode;
}
private BinaryNode<AnyType> newNode = null; // Used between different inserts
/**
* Insert into the tree.
* @param x the item to insert.
*/
public void insert( AnyType x )
{
if( newNode == null )
newNode = new BinaryNode<AnyType>( null );
newNode.element = x;
if( root == nullNode )
{
newNode.left = newNode.right = nullNode;
root = newNode;
}
else
{
root = splay( x, root );
int compareResult = x.compareTo( root.element );
if( compareResult < 0 )
{
newNode.left = root.left;
newNode.right = root;
root.left = nullNode;
root = newNode;
}
else
if( compareResult > 0 )
{
newNode.right = root.right;
newNode.left = root;
root.right = nullNode;
root = newNode;
}
else
return; // No duplicates
}
newNode = null; // So next insert will call new
}
/**
* Remove from the tree.
* @param x the item to remove.
*/
public void remove( AnyType x )
{
if( !contains( x ) )
return;
BinaryNode<AnyType> newTree;
// If x is found, it will be splayed to the root by contains
if( root.left == nullNode )
newTree = root.right;
else
{
// Find the maximum in the left subtree
// Splay it to the root; and then attach right child
newTree = root.left;
newTree = splay( x, newTree );
newTree.right = root.right;
}
root = newTree;
}
/**
* Find the smallest item in the tree.
* Not the most efficient implementation (uses two passes), but has correct
* amortized behavior.
* A good alternative is to first call find with parameter
* smaller than any item in the tree, then call findMin.
* @return the smallest item or throw UnderflowException if empty.
*/
public AnyType findMin( )
{
BinaryNode<AnyType> ptr = root;
while( ptr.left != nullNode )
ptr = ptr.left;
root = splay( ptr.element, root );
return ptr.element;
}
/**
* Find the largest item in the tree.
* Not the most efficient implementation (uses two passes), but has correct
* amortized behavior.
* A good alternative is to first call find with parameter
* larger than any item in the tree, then call findMax.
* @return the largest item or throw UnderflowException if empty.
*/
public AnyType findMax( )
{
BinaryNode<AnyType> ptr = root;
while( ptr.right != nullNode )
ptr = ptr.right;
root = splay( ptr.element, root );
return ptr.element;
}
/**
* Find an item in the tree.
* @param x the item to search for.
* @return true if x is found; otherwise false.
*/
public boolean contains( AnyType x )
{
if( isEmpty( ) )
return false;
root = splay( x, root );
return root.element.compareTo( x ) == 0;
}
/**
* Make the tree logically empty.
*/
public void makeEmpty( )
{
root = nullNode;
}
/**
* Test if the tree is logically empty.
* @return true if empty, false otherwise.
*/
public boolean isEmpty( )
{
return root == nullNode;
}
private BinaryNode<AnyType> header = new BinaryNode<AnyType>( null ); // For splay
/**
* Internal method to perform a top-down splay.
* The last accessed node becomes the new root.
* @param x the target item to splay around.
* @param t the root of the subtree to splay.
* @return the subtree after the splay.
*/
private BinaryNode<AnyType> splay( AnyType x, BinaryNode<AnyType> t )
{
BinaryNode<AnyType> leftTreeMax, rightTreeMin;
header.left = header.right = nullNode;
leftTreeMax = rightTreeMin = header;
nullNode.element = x; // Guarantee a match
for( ; ; )
{
int compareResult = x.compareTo( t.element );
if( compareResult < 0 )
{
if( x.compareTo( t.left.element ) < 0 )
t = rotateWithLeftChild( t );
if( t.left == nullNode )
break;
// Link Right
rightTreeMin.left = t;
rightTreeMin = t;
t = t.left;
}
else if( compareResult > 0 )
{
if( x.compareTo( t.right.element ) > 0 )
t = rotateWithRightChild( t );
if( t.right == nullNode )
break;
// Link Left
leftTreeMax.right = t;
leftTreeMax = t;
t = t.right;
}
else
break;
}
leftTreeMax.right = t.left;
rightTreeMin.left = t.right;
t.left = header.right;
t.right = header.left;
return t;
}
/**
* Rotate binary tree node with left child.
* For AVL trees, this is a single rotation for case 1.
*/
private static <AnyType> BinaryNode<AnyType> rotateWithLeftChild( BinaryNode<AnyType> k2 )
{
BinaryNode<AnyType> k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
return k1;
}
/**
* Rotate binary tree node with right child.
* For AVL trees, this is a single rotation for case 4.
*/
private static <AnyType> BinaryNode<AnyType> rotateWithRightChild( BinaryNode<AnyType> k1 )
{
BinaryNode<AnyType> k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
return k2;
}
// Basic node stored in unbalanced binary search trees
private static class BinaryNode<AnyType>
{
// Constructors
BinaryNode( AnyType theElement )
{
this( theElement, null, null );
}
BinaryNode( AnyType theElement, BinaryNode<AnyType> lt, BinaryNode<AnyType> rt )
{
element = theElement;
left = lt;
right = rt;
}
AnyType element; // The data in the node
BinaryNode<AnyType> left; // Left child
BinaryNode<AnyType> right; // Right child
}
private BinaryNode<AnyType> root;
private BinaryNode<AnyType> nullNode;
// Test program; should print min and max and nothing else
public static void main( String [ ] args )
{
mySplayTree<Integer> t = new mySplayTree<Integer>( );
final int NUMS = 40000;
final int GAP = 307;
System.out.println( "Checking... (no bad output means success)" );
for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS )
t.insert( i );
System.out.println( "Inserts complete" );
for( int i = 1; i < NUMS; i += 2 )
t.remove( i );
System.out.println( "Removes complete" );
if( t.findMin() != 2 || t.findMax() != NUMS - 2 )
System.out.println( "FindMin or FindMax error!" );
for( int i = 2; i < NUMS; i += 2 )
if( !t.contains( i ) )
System.out.println( "Error: find fails for " + i );
for( int i = 1; i < NUMS; i += 2 )
if( t.contains( i ) )
System.out.println( "Error: Found deleted item " + i );
}
}