avl trees
play

AVL Trees Section 4.4 39 AVL Tree A balanced tree Ensures log - PowerPoint PPT Presentation

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. AVL Trees Section 4.4 39

  2. 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

  3. Balanced Tree Height(null) = -1 Height(root->left) = 4 Height(root->right) Too weak 3 5 2 6 1 7 41

  4. Balanced Tree Height(null) = -1 Height(node->left) = 4 Height(node->right) Could be impossible 2 6 to satisfy 3 1 5 7 42

  5. AVL Balance Condition πΌπ‘“π‘—π‘•β„Žπ‘’ π‘œπ‘π‘’π‘“ β†’ π‘šπ‘“π‘”π‘’ βˆ’ πΌπ‘“π‘—π‘•β„Žπ‘’ π‘œπ‘π‘’π‘“ β†’ π‘ π‘—π‘•β„Žπ‘’ ≀ 1 5 Height(null) = -1 3 6 2 4 7 1 43

  6. AVL Example 5 2 7 4 1 6 3 Is this an AVL Tree? Yes 44

  7. AVL Example 5 Violating node 4 6 2 7 1 3 Is this an AVL Tree? No 45

  8. AVL Example Is this an AVL Tree? Yes 46

  9. 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

  10. 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

  11. 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

  12. 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

  13. 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

  14. 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