Download presentation
Presentation is loading. Please wait.
Published byNathan Mosley Modified over 8 years ago
1
AVL Trees 1
2
Balancing a BST Goal – Keep the height small – For any node, left and right sub-tree have approximately the same height Ensures fast (O(lgn)) inserts, deletes and searches Rotate entries to balance the tree 2
3
Types of Rotations Left (right) rotate – Use if height of right (left) subtree of right (left) child is too large Left-right (right-left) rotate Double right (left) rotate – Use if height of right (left) subtree of left (right) child is too large 3
4
Left Rotation 4 x y T1T1 T2T2 T3T3 y x T1T1 T2T2 T3T3
5
Right-Left Rotation (Double-Left Rotation) 5 x T4T4 x T1T1 T2T2 T3T3 z T4T4 y z T1T1 y T2T2 T3T3 T1T1 T2T2 z yx T3T3 T4T4
6
When to Balance a Tree? 6 How to determine when to balance a tree? AVL – based directly on height of subtrees IPR – keep track of number of nodes in each subtree Red-black Splay – most frequently accessed is near the root
7
AVL Trees First proposed balanced BST (1962) Invented by Adel'son-Vel'skii and Landis For each node in the tree the difference in height between the left and right sub-tree is at most 1. Keep track of balance factor to see if rotation is required. 7
8
Example 8 70 20150 1040130 30 0 00 1
9
Balance Factor - Insert Traverse the tree and insert new leaf Traverse back up the tree, recomputing balance factor Balance factor – height of right subtree – height of left subtree 9
10
AVL Tree Requirement Balance factor must be -1, 0 or 1 If balance factor < -1 then left subtree too large If balance factor > 1 then right subtree too large 10
11
AVL Tree Rotations – Zig-zig Parent (x) balance factor is 2 (-2) Right (left) child (y) balance factor is 1 (-1) Left (right) rotate – Balance factor of x set to 0 – Balance factor of y set to 0
12
AVL Tree Rotations – Zig-zag-zig Parent (x) balance factor is 2 (-2) Right child (y) balance factor is -1 (1) Left grand-child (z) balance factor is 1 (-1) Double left (right) rotate – Balance factor z (new root) set to 0 – Balance factor y (right (left) child) set to 0 – Balance factor x (left (right) child) set to -1 (1)
13
AVL Tree Rotations – Zig-zag-zag Parent (x) balance factor is 2 (-2) Right (left) child (y) balance factor is -1 (1) Left (right) grandchild (z) balance factor is -1 (1) Double left (right) rotate – Balance factor z (new root) set to 0 – Balance factor y (right (left) child) set to -1 (1) – Balance factor x (left (right) child) set to 0
14
Height of an AVL Tree lg(n+1) h 1.44 lg(n+2) -.328 h (lg n) Inserting, deleting and searching: O(lg n) 14
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.