120 likes | 222 Views
Left Rotations. Right subtree is deeper than the left subtree so that the balance factor at node X becomes +2. (Node X is the node about which the rotation will occur.). 24. +1. 10. +1. 46. +2. 15. 0. 65. +1. 80. 0. X. AVL tree unbalanced at node 46.
E N D
Left Rotations Right subtree is deeper than the left subtree so that the balance factor at node X becomes +2. (Node X is the node about which the rotation will occur.)
24 +1 10 +1 46 +2 15 0 65 +1 80 0 X • AVL tree unbalanced at node 46. • The +2 balance factor indicates need for a left rotation.
24 +1 10 +1 65 +2 15 0 46 +1 80 0 X 2. (a) Child node 65 interchanges with parent 46. (b) Resulting tree is not a valid search tree.
24 0 10 +1 65 0 15 46 80 0 0 0 3. (a) Node 46 must become a left child of 65. (b) Node 80 moves up one level in right subtree of 65. (c) Balance factors are recomputed. AVL tree is balanced.
Right Rotations Left subtree is deeper than the right subtree so that the balance factor at node X becomes -2. (Node X is the node about which the rotation will occur.)
54 -1 80 -1 46 -2 65 0 35 -1 20 0 X • Tree is unbalanced at node containing 46. • Balance factor of –2 indicates need for a right rotation.
54 -1 80 -1 35 -2 65 0 46 -1 20 0 X 2. (a) Node 35 interchanges with parent node 46. (b) Resulting tree is not a valid search tree.
0 54 80 35 -1 0 65 20 46 0 0 0 3. (a) Node 46 must become a right child of node 35. (b) Node 20 remains left child of 35 but moves up 1 level. (c) Balance factors are recomputed. AVL tree is balanced.
Double Rotations • Insertion occurs in either: • In the right subtree of the left child of node X. • or • (2) In the left subtree of the right child of node X. • (Node X is the node which becomes unbalanced)
12 -2 8 16 -2 -1 X 4 10 +1 0 14 0 2 6 0 -1 5 0 • Tree is unbalanced at node containing 8 due to insertion • of node 5 into right subtree of left child of node 8.
12 -2 8 16 -2 -1 X 6 10 -2 0 14 0 4 0 2 5 0 0 2. (a) Rotate X’s grandchild about X’s child (rotate 6 about 4). (b) Resulting tree is not AVL balanced.
12 -1 6 16 0 -1 X 4 8 +1 0 14 0 2 5 10 0 0 0 3. (a) Rotate 6 about 8. (Rotate X’s new child about X.) (b) Tree becomes AVL balanced.