Sei sulla pagina 1di 17

SPLAY

Tree

by

P.VASUKI
Splay Tree
• Special type of Binary Search tree –
Self Adjusting balanced tree.
• Tree adjusts itself after every insert,
delete and find
• Works better with Amortized
(Average analysis) running time
Splay Tree
• The node recently accessed may be
needed in near future(locality
concept)
• Moving the recently accessed node
nearer to the root reduces further
processing time.
• Tree Structure is not balanced
always
Splaying
• After a node is accessed(insert/find),
it is splayed to the root (Moving that
node to root)
• Doing this way makes the tree
balanced over a period of time
Splay Tree Terminology

• Let X be a non-root node with ≥ 2 ancestors.


• P is its parent node.
• G is its grandparent node.

G G G G

P P P P

X X X X
Zig-Zig and Zig-Zag
Parent and grandparent Parent and grandparent
in same direction. in different directions.

Zig-zig 4
G
G 5
P 5
Zig-zag
1 P
X 2
X Similar to dog-Leg like
structure

6
Splay Tree Operations
When X is accessed, apply one of six rotation routines.

• Single Rotations (X has a P (the root) but no G)


1. ZigFromLeft,
2. ZigFromRight
• Double Rotations (X has both a P and a G)
3. ZigZigFromLeft
4. ZigZigFromRight
5. ZigZagFromLeft
6. ZigZagFromRight
Zig at depth 1 (root)
• “Zig” is just a single rotation, as in an AVL
tree
• Let R be the node that was accessed (e.g.
using Find)
root

ZigFromLeft

• ZigFromLeft moves R to the top →faster


access next time
Example : Courtesy :Washington University
Zig at depth 1
• Suppose Q is now accessed using Find

root

ZigFromRight

• ZigFromRight moves Q back to the top

9
Zig-Zag operation

• “Zig-Zag” consists of two rotations of the


opposite direction (assume R is the node
that was accessed)

(ZigFromRight) (ZigFromLeft)

ZigZagFromLeft

Example : Courtesy :Washington University 10


Zig-Zig operation

• “Zig-Zig” consists of two single


rotations of the same direction (R
is the node that was accessed)

(ZigFromLeft) (ZigFromLeft)

ZigZigFromLeft

Example : Courtesy :Washington University 11


Decreasing depth -
"autobalance"

Find(T) Find(R)

12
Example Insert
• Inserting in order 1,2,3,…,8
• Without self-adjustment

1
2 O(n2) time for n Insert
3
4
5
6
7
Example : Courtesy :Washington University 8
With Self-Adjustment

1 1

ZigFromRight
2 1 2
2 1

3
3 2 ZigFromRight
2
1 3
1

Example : Courtesy :Washington University 14


With Self-Adjustment

4 3
4
2 4 ZigFromRight
3
1
2
1

Each Insert takes O(1) time therefore O(n) time for n Insert!!

Example : Courtesy :Washington University


15
Example Deletion

10 splay (Zig-Zag) 8
5 15 5 10

2 8 13 20 2 6 9 15

13 20
6 9
Splay (zig) remove
6
attach 5 10
5 10

15 2 6 9 15
2 9

13 20 13 20

16
Note on Splay Tree
• Good at locality concepts – Recently
accessed node will be at the top.
• Better in Amortized analysis

Potrebbero piacerti anche