Data Structures and Algorithms • C# examples
AVL Trees, Red-Black Trees, and Self-Balancing Search
Keep ordered-tree height logarithmic through rotations and balance rules.
Concept
Self-balancing trees maintain constraints after updates so that the height remains O(log n). AVL trees use tighter height balance, while red-black trees use color properties that allow a different update/search trade-off. Rotations preserve the in-order key sequence while changing local shape.
How to approach it
Identify the violated balance condition, select the single or double rotation, and verify ordering before and after the rotation.
Complexity
Search, insertion, and deletion O(log n) when balance invariants are preserved.
C# example
// Right rotation around y:
x = y.Left;
y.Left = x.Right;
x.Right = y;
Expected result or behavior
The rotation promotes the left child while preserving the in-order sequence.
Practice exercise
Draw an unbalanced left-right case and identify why a double rotation is needed.
Key takeaway: Balancing is a set of maintained invariants, not a one-time tree cleanup.