Tree Rotations & Splay Trees
BST Structure
• BST's only perform well when balanced• But common cases lead
to unbalanced trees
Restoring Balance
• How could this unbalanced tree be balanced?
Restoring Balance
• How could this unbalanced tree be balanced?
Rotation
• Parent node become child, child becomes parent– Right rotation : Everyone moves right (clockwise)– Left rotation : Counter clockwise
Rotation Description
• Describe rotations by parent– Rotate 38 right
– Rotate 21 right
Child Issues
• Want to rotate 38 right (make 21 parent)– Where does 26 go?
Child Issues
• Right child of old child left child of old parent
Right Rotation
Left Rotation
Multi Step
• Want to balance this tree:
Multi Step
• Want to balance this tree:– Rotate root right is just as bad:
Multi Step
• Want to balance zig-zag pattern
Multi Step
• Want to balance zig-zag pattern– Rotate child of root left
Multi Step
• Want to balance zig-zag pattern– Rotate child of root left– Rotate root right
Deciding What to Rotate
• Figuring out where to rotate is tough– Need more info than available locally in BST• AVL, RB
Deciding What to Rotate
• Figuring out where to rotate is tough– Need more info than available locally in BST• AVL, RB
• Alternative:– Keep recent nodes at top of tree– Do a pretty good job balancing
Splay Tree
• Splaying : move node to root using rotates• Splay Tree : after any access, move node to
root– O(1) to access same element again– Faster to access nearby values– Amortized O(logn) average access
How it works:
• Insert 1-6 in order BST:http://www.cs.usfca.edu/~galles/visualization/BST.html
• Insert 1-6 in order Splay Tree:http://www.cs.usfca.edu/~galles/visualization/SplayTree.html
Splay Algorithm
• Rotating upwards to root does not always balance tree:
Find 1
• Insert 1-6, Find 1:
Find 1
• Insert 1-6, Find 1:
Zig-Zig and Zig-Zag
• Rotations done in 3 ways– Node is right below root: Zig (Rotate left or right)
Zig-Zig and Zig-Zag
• Rotations done in 3 ways– Path to node is left-left or right-right:
Zig-Zig (Rotate grandparent, then rotate parent)
Zig-Zig and Zig-Zag
• Rotations done in 3 ways– Path to node is left-right or right-left:
Zig-Zag (Rotate parent one way, then grand parent other way)
Sample:
• Splay 42
Sample:
• Splay 42– It is left-left child : Zig-Zig
Sample:
• Splay 42– It is left-left child : Zig-Zig• Rotate 52 right
Sample:
• Splay 42– It is left-left child : Zig-Zig• Rotate 52 right, rotate 47 right
Sample:
• Splay 42– Now it is a left-right child : Zig-Zag
Sample:
• Splay 42– Now it is a left-right child : Zig-Zag• 35 Rotates left
Sample:
• Splay 42– Now it is a left-right child : Zig-Zag• 35 Rotates left, 70 rotate right