Download presentation
Presentation is loading. Please wait.
1
Tree Rotations & Splay Trees
2
BST Structure BST's only perform well when balanced
But common cases lead to unbalanced trees
3
Restoring Balance How could this unbalanced tree be balanced?
4
Restoring Balance How could this unbalanced tree be balanced?
5
Rotation Parent node become child, child becomes parent
Right rotation : Everyone moves right (clockwise) Left rotation : Counter clockwise
6
Rotation Description Describe rotations by parent Rotate 38 right
7
Child Issues Want to rotate 38 right (make 21 parent)
Where does 26 go?
8
Child Issues Right child of old child left child of old parent
9
Right Rotation
10
Left Rotation
11
Multi Step Want to balance this tree:
12
Multi Step Want to balance this tree:
Rotate root right is just as bad:
13
Multi Step Want to balance zig-zag pattern
14
Multi Step Want to balance zig-zag pattern Rotate child of root left
15
Multi Step Want to balance zig-zag pattern Rotate child of root left
Rotate root right
16
Deciding What to Rotate
Figuring out where to rotate is tough Need more info than available locally in BST AVL, RB
17
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
18
Recent to Top Simple Rotating upwards to root does not balance tree:
19
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
20
How it works: Insert 1-6 in order BST: /BST.html Insert 1-6 in order Splay Tree: /SplayTree.html
21
Zig-Zig and Zig-Zag Rotations done in 3 ways
Node is right below root: Zig (Rotate left or right)
22
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)
23
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)
24
Sample: Splay 42
25
Sample: Splay 42 It is left-left child : Zig-Zig
26
Sample: Splay 42 It is left-left child : Zig-Zig Rotate 52 right
27
Sample: Splay 42 It is left-left child : Zig-Zig
Rotate 52 right, rotate 47 right
28
Sample: Splay 42 Now it is a left-right child : Zig-Zag
29
Sample: Splay 42 Now it is a left-right child : Zig-Zag
35 Rotates left
30
Sample: Splay 42 Now it is a left-right child : Zig-Zag
35 Rotates left, 70 rotate right
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.