splay trees cse 331 section 2 james daly. reminder homework 2 is out due thursday in class project 2...
TRANSCRIPT
Splay Trees
CSE 331Section 2James Daly
Reminder
• Homework 2 is out• Due Thursday in class
• Project 2 is out• Covers tree sets• Due next Friday at midnight
Review: Binary Tree
• Every node has at most 2 children• Left and right child
• Variation: n-ary trees have at most n children
Review: Binary Search Tree
• For every node• Left descendents smaller (l ≤ k)• Right descendents bigger (r ≥ k)
k
<k >k
Review: AVL Trees
• Named for Adelson-Velskii & Landis• Self-balancing binary search tree• Goal:
• Keep BST in balance• Ability to check / track balance
Review: AVL Trees
• For every node, the height of both subtrees differs by at most 1.
RotateRight(&t)
// Rotates t down to the right// Brings up left childleft ← t.lefttemp = left.rightleft.right ← tt.left ← tempt ← left
Left-Left / Right-Right Case
D
Ba6
c5
e5
B
De5
c5
a6
Left-Right / Right-Left Case
F
Ba5
e4
g5
Dc5
D
Ba5
c5
Fe
4g5
Ba5
c5
e4
D
Fg5
Motivation
• Frequently we care more about how long it takes to do a string of operations than any one• O(n) isn’t too bad – if we do it only once• Want O(m log n) for m searches
• Recently used items are more likely to be called again• Basis for caches
Splay Tree
• Not kept rigorously balanced• When a node is accessed, rotate it to the
top• Next search for the same item will be very
quick• No need for extra information
• AVL Tree: Node height• Red-Black Tree: Node color
Wrong way
k1
k2
k3
k4
k5
A
B C
D
E
F
Wrong way
k2
k3
k4
k5
k1
A B
C
D
E
F
Wrong way
k2
k3
k4
k5
k1
A B C D
E
F
Wrong way
k2
k3
k4
k5
k1
A B
C D
E
F
Wrong way
k2
k3
k4
k5k1
A B
C D
E
F
Problem
• K3 was pushed down almost as far as K2 came up.
• Easy to show that you could keep selecting bad nodes• O(n2) time total.
• Need a smarter way to do this
Splaying
• Find X• If root, done• If parent(X) = root, rotate up• Otherwise, X has both parent and grandparent
• Two cases: Zig-Zag and Zig-Zig
Zig-Zag
X
P
G
A
B C
D
X
P G
A CB D
Zig-Zig
X
P
G
A B
C
D
X
P
G
A
B
C D
Splaying
• Tends to reduce the height of the tree• Many items will be half as deep as before• Some items may be at most 2 deeper than
before
Right way
k1
k2
k3
k4
k5
A
B C
D
E
F
Right way
k1
k2
k3
k4
k5
A CB D
E
F
Right way
k1
k2
k3
k4
k5A
C
B
D E F
Insertion
• Insert X as normal for a BST• Splay X to the top
Deletion
• Remove X as normal for a BST• Splay its parent to the top