AVL Trees Section 4.4 39
AVL Tree A balanced tree Ensures π log π running time for search, insert, and delete A simple and relaxed definition for balance log π β€ β β€ log π : Too restrictive 40
Balanced Tree Height(null) = -1 Height(root->left) = 4 Height(root->right) Too weak 3 5 2 6 1 7 41
Balanced Tree Height(null) = -1 Height(node->left) = 4 Height(node->right) Could be impossible 2 6 to satisfy 3 1 5 7 42
AVL Balance Condition πΌπππβπ’ ππππ β ππππ’ β πΌπππβπ’ ππππ β π ππβπ’ β€ 1 5 Height(null) = -1 3 6 2 4 7 1 43
AVL Example 5 2 7 4 1 6 3 Is this an AVL Tree? Yes 44
AVL Example 5 Violating node 4 6 2 7 1 3 Is this an AVL Tree? No 45
AVL Example Is this an AVL Tree? Yes 46
Balancing an AVL Tree For simplicity, we assume that we keep the height of each subtree at its root An imbalance can occur as a result of an insertion or deletion To balance an AVL tree, we carry out a rotation operation 47
Insertion Call BST.insert Update the height as you climb up to the root After each height update, check for an AVL tree violation and fix using rotation 48
Violation after Insertion Violating Node Cases 1 and 4 are symmetric Cases 2 and 3 are symmetric Case 1 Case 2 Case 3 Case 4 + New Node 49
Case 1 β Single Rotation Violating Node k 2 k 1 Rotation k 1 k 2 Z X Y Y Z X Status upon insertion in X Is this a BST? Yes k 2 is in violation Is this an AVL Tree? Yes 50
Case 2 β Single Rotation? Violating Node k 2 k 1 Single k 1 k 2 Rotation Z X X Z Y Y Status upon insertion in Y Is this a BST? Yes k 2 is in violation Is this an AVL Tree? No 51
Case 2 β Double Rotation Violating Node k 3 k 2 k 1 k 1 k 3 D k 2 B C A D A B C 52
Recommend
More recommend