Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures Lecture 21 Sohail Aslam.

Similar presentations


Presentation on theme: "Data Structures Lecture 21 Sohail Aslam."— Presentation transcript:

1 Data Structures Lecture 21 Sohail Aslam

2 AVL Tree Building Example
Insert(3) single left rotation 1 -2 2 3

3 AVL Tree Building Example
Insert(3) 2 1 3 End of lecture 20

4 AVL Tree Building Example
Insert(4) 2 1 3 4

5 AVL Tree Building Example
Insert(5) 2 1 3 -2 4 5

6 AVL Tree Building Example
Insert(5) 2 1 4 3 5

7 AVL Tree Building Example
Insert(6) 2 -2 1 4 3 5 6

8 AVL Tree Building Example
Insert(6) 4 2 5 1 3 6

9 AVL Tree Building Example
Insert(7) 4 2 5 -2 1 3 6 7

10 AVL Tree Building Example
Insert(7) 4 2 6 1 3 5 7

11 AVL Tree Building Example
Insert(16) 4 2 6 1 3 5 7 16

12 AVL Tree Building Example
Insert(15) 4 2 6 1 3 5 7 -2 16 15

13 AVL Tree Building Example
Insert(15) 4 2 6 1 3 5 16 -2 7 15

14 Cases for Rotation Single rotation does not seem to restore the balance. The problem is the node 15 is in an inner subtree that is too deep. Let us revisit the rotations.

15 Cases for Rotation Let us call the node that must be rebalanced .
Since any node has at most two children, and a height imbalance requires that ’s two subtrees differ by two (or –2), the violation will occur in four cases:

16 Cases for Rotation An insertion into left subtree of the left child of . An insertion into right subtree of the left child of . An insertion into left subtree of the right child of . An insertion into right subtree of the right child of .

17 Cases for Rotation The insertion occurs on the “outside” (i.e., left-left or right-right) in cases 1 and 4 Single rotation can fix the balance in cases 1 and 4. Insertion occurs on the “inside” in cases 2 and 3 which single rotation cannot fix.

18 Cases for Rotation Single right rotation to fix case 1.   k2 k1 k1
Z X Level n-2 Z X Y Y Level n-1 new Level n new

19 Cases for Rotation Single left rotation to fix case 4. k1 k2 X Y Z k2
Level n-2 X Y Level n-1 Level n

20 Cases for Rotation Single right rotation fails to fix case 2.   k2
Z Level n-2 X Y Y Z Level n-1 new new Level n


Download ppt "Data Structures Lecture 21 Sohail Aslam."

Similar presentations


Ads by Google