110 likes | 272 Views
AVL Tree Rotations. About Rotations. A right rotation can be done on any node having a left child. A left rotation can be done on any node having a right child. A rotation always preserves the BST invariants. It might or might not decrease the height of the subtree. Parent. Parent.
E N D
About Rotations • A right rotation can be done on any node having a left child. • A left rotation can be done on any node having a right child. • A rotation always preserves the BST invariants. • It might or might not decrease the height of the subtree.
Parent Parent "Rotated Node" "Pivot" K K "Rotated Node" "Pivot" J J R(K) R(K) R(J) R(J) L(J) L(J) Right child of J, R(J), flips over to become left child of K. A Right Rotation The triangles represent arbitrary subtrees that are not modified by the rotation.
Add MA Slide from last class. New node in the right subtree of the left child of the unbalanced node. The subtree rooted at PA is now unbalanced. We need to do a right rotation at PA. But we can’t do that immediately with a simple right rotation. We need to do a left rotation at GA first. This is a left-right rotation.
root -2 +1 Right Rotation at PA • Actually we could do an immediate right rotation at PA. root But it wouldn't result in a balanced tree.
root root Preliminary Left Rotation at Left Child New node is in the right subtree of the left child of the unbalanced node. +2 +1 0 0 Left rotation of left child of unbalanced node as a preliminary step increases the height of the left subtree of the left child of the unbalanced node.
After Right Rotation at PA Now the right rotation at PA results in a balanced tree.
Fact About Rotations • In any rotation, all nodes maintain their in-order positions. • Will be in the same column in our vertical display. • Not so obvious in these diagrams because they are compacted in the left to right dimension.
Output of display_v Requires a left-right double rotation at PA Rotate left at GA. Then rotation right a PA.
After Left Rotation at GA OH has moved up to become parent of GA. MA has flipped over to become right child of GA. Now we are ready to do the right rotation at PA.